>>> 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)做不同的事情.另外,为什么要将+=字符串拆分成要插入列表的字符?
aList += 'chicken'是python的简写aList.extend('chicken').之间的区别a += b和a = 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)
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |