【问题标题】:Why does adding to a list do different things? [duplicate]为什么添加到列表会做不同的事情? [复制]
【发布时间】:2012-04-13 23:28:08
【问题描述】:
>>> aList = []
>>> aList += 'chicken'
>>> aList
['c', 'h', 'i', 'c', 'k', 'e', 'n']
>>> aList = aList + 'hello'


Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    aList = aList + 'hello'
TypeError: can only concatenate list (not "str") to list

我不明白为什么 list += (something)list = list + (something) 会做不同的事情。另外,为什么+= 将字符串拆分为要插入到列表中的字符?

【问题讨论】:

  • 另一个类似的问题stackoverflow.com/q/9766387/776084.
  • @agf:不,这个问题是关于 +=+ 面对对同一个列表的多次引用。
  • 在我看来不太像复制品。

标签: python list


【解决方案1】:

list.__iadd__() 可以采用任何可迭代对象;它对其进行迭代并将每个元素添加到列表中,从而将字符串拆分为单个字母。 list.__add__() 只能取一个列表。

【讨论】:

    【解决方案2】:

    aList += 'chicken'aList.extend('chicken') 的python 简写。 a += ba = a + b 之间的区别在于 python 在调用 add 之前尝试使用 += 调用 iadd。这意味着alist += foo 将适用于任何可迭代的 foo。

    >>> a = []
    >>> a += 'asf'
    >>> a
    ['a', 's', 'f']
    >>> a += (1, 2)
    >>> a
    ['a', 's', 'f', 1, 2]
    >>> d = {3:4}
    >>> a += d
    >>> a
    ['a', 's', 'f', 1, 2, 3]
    >>> a = a + d
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    TypeError: can only concatenate list (not "dict") to list
    

    【讨论】:

      【解决方案3】:

      要解决您的问题,您需要将列表添加到列表中,而不是将字符串添加到列表中。

      试试这个:

      a = []
      a += ["chicken"]
      a += ["dog"]
      a = a + ["cat"]
      

      请注意,它们都按预期工作。

      【讨论】:

      • 不,作为strings 的iterable
      猜你喜欢
      • 2011-09-17
      • 2014-06-16
      • 2019-12-30
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多