2011-01-09 44 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)