简体   繁体   English

如何对列表中的每个元素求和?

[英]How do a sum a value to every element in a list?

I have a list:我有一个清单:

list = [10, 15,14,20]

And I would like to sum a variable(lets say add=5) to all elements in that list, to have something like:而且我想对该列表中的所有元素求和一个变量(让我们说 add=5),得到类似的东西:

newlist = [15,20,19,25]

Thanks for your help.谢谢你的帮助。

List comprehension:列表理解:

l = [10, 15, 14, 20]
nl = [i + 5 for i in l]

Map function: Map function:

l = [10, 15, 14, 20]
nl = list(map(lambda i: i+5, l))
print(nl)
[15, 20, 19, 25]

Don't use list keyword不要使用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

You override the function list by a list:您通过列表覆盖 function list

>>> type(list)
type

>>> list = [10, 15, 14, 20]

>>> type(list)
list

Using list comprehension is probably the most pythonic way of doing this.使用列表推导可能是最 Pythonic 的方式。

Like in Corralien's answer (which is very good by the way).就像 Corralien 的回答一样(顺便说一句,这很好)。

l = [10, 15,14,20]

l = [value+5 for value in l]

This will result in:这将导致:

l = [15, 20, 19, 25]

In case you don't know how list comprehension works exactly you can break it down into tokens.如果您不知道列表理解是如何工作的,您可以将其分解为标记。

The first part value+5 is essentially what is in the for loop and it is what's being appended to the list, and for value in l is just a for loop and goes through each element in list and assigns it to the the variable value第一部分value+5本质上是 for 循环中的内容,它是附加到列表中的内容,而for value in l只是一个 for 循环,遍历列表中的每个元素并将其分配给变量value

You can use you any type of loop for this.您可以为此使用任何类型的循环。

For example with list comprehension:例如列表理解:

list = [10, 15,14,20]
x = 5
new_list = [i+x for i in list]
print(new_list)

First, you shadowed the list function by using it as a variable.首先,您通过将list function 用作变量来隐藏列表。 You can use a loop.您可以使用循环。

list1= [10, 15,14,20]
num1=5
new_l=[num+num1 for num in list1]
print(new_l)

if in case you are looking for pandas solution, as you have pandas tag in your question.如果您正在寻找 pandas 解决方案,因为您的问题中有 pandas 标签。 below solution will help you.以下解决方案将为您提供帮助。

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

Output: Output:

A
0  15
1  20
2  19
3  25

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM