问题:如何为列表中的每个元素添加一个整数?
如果我有list=[1,2,3]
并且想要添加1
到每个元素以获取输出[2,3,4]
,我该怎么做?
我假设我会使用for循环,但不确定具体如何。
If I have list=[1,2,3]
and I want to add 1
to each element to get the output [2,3,4]
,
how would I do that?
I assume I would use a for loop but not sure exactly how.
回答 0
new_list = [x+1 for x in my_list]
new_list = [x+1 for x in my_list]
回答 1
回答 2
列表理解中的其他答案可能是简单加法的最佳选择,但是如果您有一个更复杂的函数需要将其应用于所有元素,则可以进行映射可能是一个不错的选择。
在您的示例中,它将是:
>>> map(lambda x:x+1, [1,2,3])
[2,3,4]
The other answers on list comprehension are probably the best bet for simple addition, but if you have a more complex function that you needed to apply to all the elements then map may be a good fit.
In your example it would be:
>>> map(lambda x:x+1, [1,2,3])
[2,3,4]
回答 3
如果要使用numpy,则还有另一种方法,如下所示
import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)
if you want to use numpy there is another method as follows
import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)
回答 4
编辑:这不是就地
首先,不要在变量中使用单词“列表”。它遮盖了关键字list
。
最好的方法是使用拼接来完成它,请注意[:]
表示拼接:
>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]
Edit: this isn’t in-place
Firstly don’t use the word ‘list’ for your variable. It shadows the keyword list
.
The best way is to do it in place using splicing, note the [:]
denotes a splice:
>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]
回答 5
>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]
我的目的是要揭示列表中的项目是否为整数,它支持各种内置函数。
>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]
My intention here is to expose if the item in the list is an integer it supports various built-in functions.
回答 6
Python 2+:
>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]
Python 3+:
>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]
Python 2+:
>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]
Python 3+:
>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]
回答 7
import numpy as np
np.add([1, 2, 3], 1).tolist()
这使
[2, 3, 4]
import numpy as np
np.add([1, 2, 3], 1).tolist()
which gives
[2, 3, 4]
回答 8
遇到了一种效率不高但独特的方法。因此可以共享它,是的,它需要额外的空间来存储另一个列表。
from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)
res_list = list(map(add, test_list1, test_list2))
print(test_list1)
print(test_list2)
print(res_list)
#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]
Came across a not so efficient, but unique way of doing it. So sharing it across.And yes it requires extra space for another list.
from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)
res_list = list(map(add, test_list1, test_list2))
print(test_list1)
print(test_list2)
print(res_list)
#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]
回答 9
list = [1,2,3,4,5]
for index in range(5):
list[index] = list[index] +1
print(list)
list = [1,2,3,4,5]
for index in range(len(list)):
list[index] = list[index] +1
print(list)
回答 10
上面的许多答案都很好。我也看到了一些奇怪的答案,可以胜任这项工作。另外,最后看到的答案是通过正常循环。这种愿意给出答案的意愿将我引向itertools
和numpy
,它们将以不同的方式完成相同的工作。
在这里,我介绍了完成此工作的不同方法,以上未作回答。
import operator
import itertools
x = [3, 5, 6, 7]
integer = 89
"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
print(i, end = ",")
# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)
# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy
res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape
# if you specifically want a list, then use tolist
res_list = res.tolist()
print(res_list)
输出量
>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96, # output of iterating above starmap object
>>> [92, 94, 95, 96] # output obtained by casting to list
>>> __
>>> # |\ | | | |\/| |__| \ /
>>> # | \| |__| | | | |
>>> [92 94 95 96] # this is numpy.ndarray object
>>> (4,) # shape of array
>>> [92, 94, 95, 96] # this is a list object (doesn't have a shape)
我唯一强调使用numpy
是,应该始终对numpy之类的库进行此类操作,因为它对于大型数组而言性能高效。
Many of the answers above are very good. I’ve also seen some weird answers that will do the job. Also, the last answer seen was through a normal loop. This willingness to give answers leads me to itertools
and numpy
, which will do the same job in a different way.
Here I present different ways to do the job, not answered above.
import operator
import itertools
x = [3, 5, 6, 7]
integer = 89
"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
print(i, end = ",")
# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)
# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy
res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape
# if you specifically want a list, then use tolist
res_list = res.tolist()
print(res_list)
Output
>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96, # output of iterating above starmap object
>>> [92, 94, 95, 96] # output obtained by casting to list
>>> __
>>> # |\ | | | |\/| |__| \ /
>>> # | \| |__| | | | |
>>> [92 94 95 96] # this is numpy.ndarray object
>>> (4,) # shape of array
>>> [92, 94, 95, 96] # this is a list object (doesn't have a shape)
My sole reason to highlight the use of numpy
is that one should always do such manipulations with libraries like numpy because it is performance efficient for very large arrays.