为什么添加到列表中会做不同的事情?

kkS*_*der 13 python list

>>> 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
Run Code Online (Sandbox Code Playgroud)

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

Ign*_*ams 5

list.__iadd__()可以采取任何迭代; 它迭代它并将每个元素添加到列表中,这导致将字符串拆分为单个字母.list.__add__()只能拿一份清单.


Nol*_*lty 5

aList += 'chicken'是python的简写aList.extend('chicken').之间的区别a += ba = a + b是蟒蛇试图调用iadd+=调用之前add.这意味着它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
Run Code Online (Sandbox Code Playgroud)