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?
如果我有list=[1,2,3]我想给每个元素加1以得到输出[2,3,4],我该怎么做?
I assume I would use a for loop but not sure exactly how.
我假设我会使用for循环,但不确定具体是如何使用的。
7 个解决方案
#1
86
new_list = [x+1 for x in my_list]
#2
14
>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>
python列表理解。
#3
12
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.
列表理解的其他答案可能是简单加法的最佳选择,但是如果您有一个更复杂的函数,需要应用于所有元素,那么map可能是一个很好的选择。
In your example it would be:
在你的例子中是:
>>> map(lambda x:x+1, [1,2,3])
[2,3,4]
#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.
我的目的是要公开列表中的项是一个整数,它支持各种内置函数。
#5
4
Python 2+:
Python 2 +:
>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]
Python 3+:
Python 3 +:
>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]
#6
4
if you want to use numpy there is another method as follows
如果您想使用numpy,还有另一个方法,如下所示
import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)
#7
3
Firstly don't use the word 'list' for your variable. It shadows the keyword list
.
首先,不要在变量中使用“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]
#1
86
new_list = [x+1 for x in my_list]
#2
14
>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>
python列表理解。
#3
12
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.
列表理解的其他答案可能是简单加法的最佳选择,但是如果您有一个更复杂的函数,需要应用于所有元素,那么map可能是一个很好的选择。
In your example it would be:
在你的例子中是:
>>> map(lambda x:x+1, [1,2,3])
[2,3,4]
#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.
我的目的是要公开列表中的项是一个整数,它支持各种内置函数。
#5
4
Python 2+:
Python 2 +:
>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]
Python 3+:
Python 3 +:
>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]
#6
4
if you want to use numpy there is another method as follows
如果您想使用numpy,还有另一个方法,如下所示
import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)
#7
3
Firstly don't use the word 'list' for your variable. It shadows the keyword list
.
首先,不要在变量中使用“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]