我有一个整数列表,我想知道是否可以添加到此列表中的单个整数。
最佳答案
这是一个示例,其中要添加的内容来自字典
>>> 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]
关于python - 添加到列表中的整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4641765/