Currently, i have four list and i want to sum them up into one list.
L1 = [2.3,4.5,6.9]
L2 = [1.2,3.5,5.4]
L3 = [12.1,6.8,2.4]
L4 = [15.2,5.9,11.7]
That would give me:
newList = [30.8,20.7,26.4]
I looked up many methods utilising zips
but I'm looking for a method to do it the long way. If there aren't any convenient method, I wouldn't mind using zips but just being curious.
Basically i would create a new list but i wasn't able to figure the sum part.
newL = []
for val in L1:
for val in L2:??
You can use zip like this:
[sum(t) for t in zip(L1, L2, L3, L4)]
# [30.799999999999997, 20.700000000000003, 26.4]
Assuming that all four lists have the same length, alternative solutions are:
list comprehensions:
sumsList = [L1[i]+L2[i]+L3[i]+L4[i] for i in range(len(L1))]
or , an alternative solution, far more elegant, in my opinion:
someList = [L1,L2,L3,L4] sumsList = [sum([l[i] for l in someList]) for i in range(len(L1))]
for-in
loops:
sumsList = [] for i in range(len(L1)): sumsList.append(L1[i]+L2[i]+L3[i]+L4[i])
Result: [30.799999999999997, 20.700000000000003, 26.4]
Best part: does not use zip()
>>> L = [[2.3, 4.5, 6.9],
... [1.2, 3.5, 5.4],
... [12.1, 6.8, 2.4],
... [15.2, 5.9, 11.7]]
>>> list(map(sum, zip(*L)))
[30.799999999999997, 20.700000000000003, 26.399999999999999]
I guess you can use map
, sum
and zip
:
list_sums = map(sum, zip(L1,L2,L3,L4))
# [30.799999999999997, 20.700000000000003, 26.4]
If you don't want to change the end product then a tuple is constructed much faster than a list, expressing tuple() before a generator as below:
total_of_each_element = tuple(sum(t) for t in zip(L1,L2,L3,L4))
will achieve this, here's my code
L1 = [2.3,4.5,6.9]
L2 = [1.2,3.5,5.4]
L3 = [12.1,6.8,2.4]
L4 = [15.2,5.9,11.7]
total_of_each_element = tuple(sum(t) for t in zip(L1,L2,L3,L4))
print (total_of_each_element)
prints:
(30.799999999999997, 20.700000000000003, 26.4)
to round it:
total_of_each_element = tuple(round(sum(t),2) for t in zip(L1,L2,L3,L4))
print (total_of_each_element)
prints:
(30.8, 20.7, 26.4)
alternatively, make all lists the same length, adding zeros to the shorter ones:
lists = [L1,L2,L3,L4]
longest = len(max(lists,key=len))
for lst in lists:
if len(lst) < longest:
n = longest - len(lst)
for i in range(n):
lst.append(0)
then total and round with a for loop:
total_of_each_element = []
for i in range(longest):
total_of_each_element.append(round((L1[i]+L2[i]+L3[i]+L4[i]),2))
print (total_of_each_element)
prints:
[30.8, 20.7, 26.4]
zip
将是最好的答案...
newList = [a + b + c + d for a,b,c,d in zip(L1,L2,L3,L4)]
You can use numpy.You just change them to numpy array and do simple addition.
import numpy as np
print np.array(L1)+np.array(L2)+np.array(L3)+np.array(L4)
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.