打印四个不同浮动列表的总和?

时间:2017-04-23 15:55:42

标签: python 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]

那会给我:

newList = [30.8,20.7,26.4]

我查找了许多使用zips的方法,但我正在寻找一种方法来完成它。如果没有任何方便的方法,我不会介意使用拉链而只是好奇。

基本上我会创建一个新列表,但我无法计算总和。

newL = []
for val in L1:
    for val in L2:??

7 个答案:

答案 0 :(得分:5)

您可以像这样使用zip:

[sum(t) for t in zip(L1, L2, L3, L4)]
# [30.799999999999997, 20.700000000000003, 26.4]

答案 1 :(得分:3)

假设所有四个列表具有相同的长度,则替代解决方案是:

  • 列表理解:

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

答案 2 :(得分:1)

>>> 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]

答案 3 :(得分:1)

我猜您可以使用mapsumzip

list_sums = map(sum, zip(L1,L2,L3,L4))
# [30.799999999999997, 20.700000000000003, 26.4]

答案 4 :(得分:1)

如果您不想更改最终产品,那么构建元组的速度比列表快得多,在生成器之前表示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]

答案 5 :(得分:0)

zip将是最好的答案......

newList = [a + b + c + d for a,b,c,d in zip(L1,L2,L3,L4)]

答案 6 :(得分:0)

您可以使用numpy。您只需将它们更改为numpy数组并进行简单的添加。

import numpy as np
print np.array(L1)+np.array(L2)+np.array(L3)+np.array(L4)