我有一个清单:
list = [10, 15,14,20]
我想对列表中的所有元素求和一个变量(比如说 add=5),得到类似的结果:
newlist = [15,20,19,25]
感谢您的帮助。
列表理解:
l = [10, 15, 14, 20]
nl = [i + 5 for i in l]
地图功能:
l = [10, 15, 14, 20]
nl = list(map(lambda i: i+5, l))
print(nl)
[15, 20, 19, 25]
不要使用
list
关键字
>>> list = [10, 15, 14, 20]
>>> list((3, 5, 7))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-644-e66a8dedf706> in <module>
----> 1 list((3, 5, 7))
TypeError: 'list' object is not callable
您通过列表覆盖函数
list
:
>>> type(list)
type
>>> list = [10, 15, 14, 20]
>>> type(list)
list
使用列表理解可能是最 Pythonic 的方法。
就像 Corralien 的回答一样(顺便说一句,这非常好)。
l = [10, 15,14,20]
l = [value+5 for value in l]
这将导致:
l = [15, 20, 19, 25]
如果您不知道列表理解的具体工作原理,您可以将其分解为标记。
第一部分
value+5
本质上是for循环中的内容,它是附加到列表中的内容,for value in l
只是一个for循环,遍历列表中的每个元素并将其分配给变量value
您可以使用任何类型的循环来实现此目的。
例如列表理解:
list = [10, 15,14,20]
x = 5
new_list = [i+x for i in list]
print(new_list)
首先,您通过将
list
函数用作变量来隐藏它。
您可以使用循环。
list1= [10, 15,14,20]
num1=5
new_l=[num+num1 for num in list1]
print(new_l)
如果您正在寻找 pandas 解决方案,因为您的问题中有 pandas 标签。以下解决方案将对您有所帮助。
import pandas as pd
alist = [10, 15,14,20] # initial list
const = 5 # constant you want to add
df= pd.DataFrame(data={"A":alist}) # create a dataframe
df["A"] += const # add constant to dataframe
print(df) # print dataframe
输出:
A
0 15
1 20
2 19
3 25
在列表较长且处理速度很重要的情况下,以下转换可能会对您有所帮助。
import numpy as np
l = [10, 15,14,20]
l=list(np.array(l)+5)