2013-08-12 81 views
1

我有類似的東西:Python列表追加不工作

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

我得到的輸出是:

... 
None 
None 
None 

我希望S包含噸。爲什麼這不適合我?

回答

12

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]