添加到列表中的整数

fan*_*gus 10 python integer list add

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

Gor*_*son 20

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

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]
Run Code Online (Sandbox Code Playgroud)

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

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]
Run Code Online (Sandbox Code Playgroud)

将整数插入列表的中间:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 10

这是一个添加内容来自字典的示例

>>> 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]
Run Code Online (Sandbox Code Playgroud)

以下是添加其他列表中元素的示例

>>> 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]
Run Code Online (Sandbox Code Playgroud)

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

L[:] = [sum(i) for i in zip(L, things_to_add)]
Run Code Online (Sandbox Code Playgroud)

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

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]
Run Code Online (Sandbox Code Playgroud)


The*_*uck 5

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]
Run Code Online (Sandbox Code Playgroud)