如何将python列表中的整数相加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13909052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:55:43  来源:igfitidea点击:

How do I add together integers in a list in python?

pythonlistintegeradd

提问by MaxwellBrahms

If I had a list like

如果我有一个像

x = [2, 4, 7, 12, 3]

What function/process would I use to add all of the numbers together?

我将使用什么函数/过程将所有数字相加?

Is there any way other than using sum ()?

除了使用sum()还有什么办法吗?

采纳答案by The Recruit

x = [2, 4, 7, 12, 3]
sum_of_all_numbers= sum(x)

or you can try this:

或者你可以试试这个:

x = [2, 4, 7, 12, 3] 
sum_of_all_numbers= reduce(lambda q,p: p+q, x)

Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing p+q, you can instead use a lambda function.

Reduce 是一种在列表的每个元素上累积执行函数的方法。它可以执行任何功能,因此如果您定义自己的模数函数,它将对列表的每个元素重复执行该功能。为了避免定义用于执行 p+q 的整个函数,您可以改用 lambda 函数。

回答by Hymancogdill

This:

这个:

sum([2, 4, 7, 12, 3])

You use sum()to add all the elements in a list.

您用于sum()添加列表中的所有元素。

So also:

所以也是:

x = [2, 4, 7, 12, 3]
sum(x)

回答by Yuanhang Guo

you can try :

你可以试试 :

x = [2, 4, 7, 12, 3]    
total = sum(x)

回答by RandomPhobia

First Way:

第一种方式:

my_list = [1,2,3,4,5]
list_sum = sum(list)

Second Way(less efficient):

第二种方式(效率较低):

my_list = [1,2,3,4,5]

list_sum = 0
for x in my_list:
   list_sum += x