python列表追加不起作用

use*_*774 1 python

我有类似的东西:

>>> S=list()
>>> T=[1,2,3]
>>> for t in T:
...     print(S.append(t))
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

...
None
None
None
Run Code Online (Sandbox Code Playgroud)

我希望S包含t.为什么这不适合我?

Ter*_*ryA 14

list.append()没有任何回报.因为它没有返回任何内容,所以默认为None(这就是为什么当你尝试打印值时,你会得到None).

它只是将项目附加到给定列表中.注意:

>>> S = list()
>>> T = [1,2,3]
>>> for t in T:
...     S.append(t)
>>> print(S)
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

另一个例子:

>>> A = []
>>> for i in [1, 2, 3]:
...     A.append(i) # Append the value to a list
...     print(A) # Printing the list after appending an item to it
... 
[1]
[1, 2]
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)