2011-01-09 45 views
4

我有一個整數列表,我想知道是否可以添加到此列表中的個別整數。添加到列表中的整數

+0

什麼意思是「添加到個人整數」 - 你想添加相同的數字給一組給定的元素,比如元素1,5,10和23? – canavanin 2011-01-09 21:04:41

回答

7

這裏是一個例子,其中t hings到加來從字典

>>> L = [0, 0, 0, 0] 
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1}) 
>>> for item in things_to_add: 
...  L[item['idx']] += item['amount'] 
... 
>>> L 
[0, 1, 1, 0] 

下面是一個例子從另一個列表中添加元素

>>> L = [0, 0, 0, 0] 
>>> things_to_add = [0, 1, 1, 0] 
>>> for idx, amount in enumerate(things_to_add): 
...  L[idx] += amount 
... 
>>> L 
[0, 1, 1, 0] 

你也可以實現上面的列表理解和zip

L[:] = [sum(i) for i in zip(L, things_to_add)] 

這裏是從元組列表中增加的一個例子

>>> things_to_add = [(1, 1), (2, 1)] 
>>> for idx, amount in things_to_add: 
...  L[idx] += amount 
... 
>>> L 
[0, 1, 1, 0] 
0

是的,這是可能的,因爲列表是可變的。

查看內置的enumerate()函數,以瞭解如何遍歷列表並查找每個條目的索引(然後可以使用該索引分配給特定的列表項)。

3
fooList = [1,3,348,2] 
fooList.append(3) 
fooList.append(2734) 
print(fooList) # [1,3,348,2,3,2734] 
16

您可以追加到一個列表的末尾:

foo = [1,2,3,4,5] 
foo.append(4) 
foo.append([8,7])  
print(foo)   #[1, 2, 3, 4, 5, 4, [8, 7]] 

您可以在列表中這樣的編輯項:

foo = [1,2,3,4,5] 
foo[3] = foo[3] + 4  
print(foo)   #[1,2,3,8,5] 

插入整數到列表的中間:

x = [2,5,10] 
x.insert(2, 77) 
print(x)    #[2, 5, 77, 10] 
0

如果您嘗試附加數字,比如說 listName.append(4),則最後會附加4。 但是,如果您嘗試拍攝<int>,然後將其追加爲num = 4,然後再輸入listName.append(num),則會出現'num' is of <int> typelistName is of type <list>錯誤。所以請在追加之前輸入int(num)