[英]How to add sums of lists in python
num_list_1 = [1,2,3,4]
sum of num_list_1 = 10 num_list_1 的总和 = 10
num_list_2 = [5,6,7,8]
sum of num_list_2 = 26 num_list_2 的总和 = 26
how would I be able to sum together num_list_1
and num_list_2
.我如何能够将
num_list_1
和num_list_2
。
I've tried doing it myself however as it is a list it wont let me concatenate them.我试过自己做,但是因为它是一个列表,它不会让我连接它们。
Get the sum of each list individually, and then sum the both scalar values to get the total_sum:分别获取每个列表的总和,然后将两个标量值相加以获得 total_sum:
In [1733]: num_list_1 = [1,2,3,4]
In [1734]: num_list_2 = [5,6,7,8]
In [1737]: sum(num_list_1) + sum(num_list_2)
Out[1737]: 36
You could sum the concatenation of the two lists:您可以对两个列表的串联求和:
sum(num_list_1+num_list_2)
This is what I get using the python console:这是我使用 python 控制台得到的:
>>>num_list_1 = [1,2,3,4]
>>>num_list_2 = [5,6,7,8]
>>>sum(num_list_1+num_list_2)
>>>36
Or you could just sum the sums:或者您可以将总和相加:
sum(num_list_1) + sum(num_list_2)
which leads to the same output but in a probably faster way:这导致相同的输出,但可能以更快的方式:
>>>num_list_1 = [1,2,3,4]
>>>num_list_2 = [5,6,7,8]
>>>sum(num_list_1) + sum(num_list_2)
>>>36
如果您有多个列表(超过 2 个),您可以通过将map
应用于结果来对sum
进行求和:
sum(map(sum,(num_list_1,num_list_2)))
+
在列表的情况下用作连接,因此sum(num_list_1 + num_list_2)
会有所帮助
num_list_1 = [1,2,3,4]
num_list_2 = [5,6,7,8]
print(sum(num_list_1) + sum (num_list_2))
print(sum(num_list_1+ num_list_2))
You can use:您可以使用:
>>> num_list_1 = [1,2,3,4]
>>> num_list_2 = [5,6,7,8]
>>> sum(num_list_1+num_list_2)
>>> 36
sum
takes an iterable, so you can use itertools.chain
to chain your lists and feed the resulting iterable to sum
: sum
需要一个可迭代对象,因此您可以使用itertools.chain
来链接您的列表并将生成的可迭代对象提供给sum
:
from itertools import chain
num_list_1 = [1,2,3,4]
num_list_2 = [5,6,7,8]
res = sum(chain(num_list_1, num_list_2)) # 36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.