[英]Printing the sum of four different list of floats?
目前,我有四个清单,我想将它们汇总成一个清单。
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]
那会给我:
newList = [30.8,20.7,26.4]
我查找了许多使用zips
的方法,但我正在寻找一种可以长期使用的方法。 如果没有任何方便的方法,我不会介意使用zip,而只是好奇。
基本上我会创建一个新列表,但我无法计算总和。
newL = []
for val in L1:
for val in L2:??
您可以像这样使用zip:
[sum(t) for t in zip(L1, L2, L3, L4)]
# [30.799999999999997, 20.700000000000003, 26.4]
假设所有四个列表的长度相同,则替代解决方案是:
清单理解:
sumsList = [L1[i]+L2[i]+L3[i]+L4[i] for i in range(len(L1))]
或 ,另一种解决方案,我认为更为优雅:
someList = [L1,L2,L3,L4] sumsList = [sum([l[i] for l in someList]) for i in range(len(L1))]
for-in
循环:
sumsList = [] for i in range(len(L1)): sumsList.append(L1[i]+L2[i]+L3[i]+L4[i])
结果: [30.799999999999997, 20.700000000000003, 26.4]
最好的部分:不使用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]
我猜你可以使用map
, sum
和zip
:
list_sums = map(sum, zip(L1,L2,L3,L4))
# [30.799999999999997, 20.700000000000003, 26.4]
如果您不想更改最终产品,则元组的构造比列表快得多,在生成器之前表示tuple()如下:
total_of_each_element = tuple(sum(t) for t in zip(L1,L2,L3,L4))
将实现这一点,这是我的代码
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)
印刷品:
(30.799999999999997, 20.700000000000003, 26.4)
四舍五入:
total_of_each_element = tuple(round(sum(t),2) for t in zip(L1,L2,L3,L4))
print (total_of_each_element)
印刷品:
(30.8, 20.7, 26.4)
或者,使所有列表具有相同的长度,在较短的列表上添加零:
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)
然后合计并以for循环取整:
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)
印刷品:
[30.8, 20.7, 26.4]
zip
将是最好的答案...
newList = [a + b + c + d for a,b,c,d in zip(L1,L2,L3,L4)]
您可以使用numpy,只需将其更改为numpy数组并进行简单加法即可。
import numpy as np
print np.array(L1)+np.array(L2)+np.array(L3)+np.array(L4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.