在列表中给整数加法
我有一个整数的列表,我在想是否可以对这个列表中的每个整数进行加法操作。
5 个回答
5
fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
20
你可以在列表的末尾添加内容:
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]
11
这里有一个例子,展示如何从字典中添加内容
>>> 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]