我有类似于以下内容:
>>> S=list()
>>> T=[1,2,3]
>>> for t in T:
... print(S.append(t))
我得到的输出是:
...
None
None
None
我期望S包含t。为什么这对我不起作用?
我有类似于以下内容:
>>> S=list()
>>> T=[1,2,3]
>>> for t in T:
... print(S.append(t))
...
None
None
None
list.append()
并不返回任何东西。因为它没有返回任何东西,所以默认为None
(这就是为什么当您尝试打印值时,会得到None
)。
它只是将项目插入给定的列表中。请观察:
>>> S = list()
>>> T = [1,2,3]
>>> for t in T:
... S.append(t)
>>> print(S)
[1, 2, 3]
另一个例子:
>>> 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]
.append()是一个列表方法,它不返回任何值,而是改变了列表。例如.index()或.count()方法会返回对象值,而.append()则改变了对象。例如:
T = [1, 2, 3]
T.append(4)
print(T)
结果: [1, 2, 3, 4]
我们可以使用 .append() 函数来修改列表 S,并向其中添加列表 T 的元素。列表 S 和 T 是两个独立的对象,它们在内存中有两个不同的地址。您可以使用 id() 函数检查这一点。
T = [1, 2, 3]
print(id(T))
S = list()
print(S)
print(id(S))
for t in T:
S.append(t)
print(S)
print(id(S))
结果:
2476978999688
[]
2476978081224
[1, 2, 3]
2476978081224
print(T)
print(id(T))
S = T
print(S)
print(id(S))
结果:
[1, 2, 3]
2476978999688
[1, 2, 3]
2476978999688