num_list_1 = [1,2,3,4]
sum of num_list_1 = 10
num_list_2 = [5,6,7,8]
sum of num_list_2 = 26
how would I be able to sum together num_list_1
and 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:
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:
>>>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
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.