-4

有一个列表如下:list = []

然后假设x = 'A',是什么list = list + [x]意思?是不是只针对人物?如果是这样,它如何适应整数?

4

3 回答 3

4

首先,使用不同的名称而不是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
>>>
于 2012-10-10T21:51:35.420 回答
1

它是列表与任何数据的连接:

>>> [1, "a", True] + ["hello", 2.3]
[1, "a", True, "hello", 2.3]
于 2012-10-10T21:51:49.630 回答
-3

lis=lis+[x]表示添加'a'[]然后将新列表存储['a']lisLHS中

但是这样做每次都会创建新对象:

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)

于 2012-10-10T21:52:22.750 回答