Python 添加到列表中的整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4641765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:41:58  来源:igfitidea点击:

Add to integers in a list

pythonlistintegeradd

提问by fangus

I have a list of integers and I was wondering if it would be possible to add to individual integers in this list.

我有一个整数列表,我想知道是否可以添加到此列表中的单个整数。

采纳答案by John La Rooy

Here is an example where the things to add come from a dictionary

这是一个示例,其中要添加的内容来自字典

>>> 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]

Here is an example adding elements from another list

这是从另一个列表添加元素的示例

>>> 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]

You could also achieve the above with a list comprehension and zip

您还可以通过列表理解和 zip 来实现上述目标

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

Here is an example adding from a list of tuples

这是从元组列表中添加的示例

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

回答by Tim Pietzcker

Yes, it is possible since lists are mutable.

是的,这是可能的,因为列表是可变的。

Look at the built-in enumerate()function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).

查看内置enumerate()函数以了解如何遍历列表并找到每个条目的索引(然后您可以使用该索引分配给特定的列表项)。

回答by The Communist Duck

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

回答by Gordon Gustafson

You can append to the end of a list:

您可以附加到列表的末尾:

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

You can edit items in the list like this:

您可以像这样编辑列表中的项目:

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

Insert integers into the middle of a list:

在列表中间插入整数:

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

回答by devDeejay

If you try appending the number like, say listName.append(4), this will append 4at last. But if you are trying to take <int>and then append it as, num = 4followed by listName.append(num), this will give you an error as 'num' is of <int> typeand listName is of type <list>. So do type cast int(num)before appending it.

如果您尝试附加数字,例如 listName.append(4),这将4最后附加。但是,如果您尝试采用<int>然后将其附加为 as,num = 4后跟listName.append(num),这会给您带来错误 as'num' is of <int> typelistName is of type <list>。所以int(num)在追加之前做类型转换。