How do I add together integers in a list in python? [closed]

▼魔方 西西 提交于 2019-12-06 04:38:57

问题


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 ()?


回答1:


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.




回答2:


This:

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

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

So also:

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



回答3:


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



回答4:


you can try :

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


来源:https://stackoverflow.com/questions/13909052/how-do-i-add-together-integers-in-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!