有一个列表如下:list = []
。
然后假设x = 'A'
,是什么list = list + [x]
意思?是不是只针对人物?如果是这样,它如何适应整数?
首先,使用不同的名称而不是list
.
那么,就试试吧。你有一个 Python shell,对吧?
>>> l = []
>>> l = l + "a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> l = l + ["a"]
>>> l
['a']
>>> l = l + [1]
>>> l
['a', 1]
>>> l = l + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>>
它是列表与任何数据的连接:
>>> [1, "a", True] + ["hello", 2.3]
[1, "a", True, "hello", 2.3]
lis=lis+[x]
表示添加'a'
到[]
然后将新列表存储['a']
在lis
LHS中
但是这样做每次都会创建新对象:
In [38]: x='a'
In [39]: lis=[]
In [40]: id(lis)
Out[40]: 154680492
In [41]: lis=lis+[x]
In [42]: lis
Out[42]: ['a']
In [43]: id(lis)
Out[43]: 154749100
更好地使用lis+=[x]
或lis.extend(x)