索引明智的多个列表列表的总和

时间:2016-03-15 06:18:29

标签: python list

考虑我有一个列表列表:

[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]]
[[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]]
[[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]

现在我想要第一个列表的索引的所有索引的总和,然后是第二个列表5+15+34=54 10+10+20=40 等等:

[54,40,50, 50,200], [20,30,75,90,180]

我试过了:

for res in results:     
    print [sum(j) for j in zip(*res)] 

此处results是列表清单。 但它给出了每个列表项的总和:

[6,19,55,73,181]
[25,11,35,27,89]
[43,40,35,40,110]

3 个答案:

答案 0 :(得分:8)

您几乎是正确的,您需要解压缩results并将其压缩。

>>> data = [[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]],
...         [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]],
...         [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]]
>>> for res in zip(*data):
...     print [sum(j) for j in zip(*res)] 
... 
[54, 40, 50, 50, 200]
[20, 30, 75, 90, 180]

你可以简单地用列表理解来写这个

>>> [[sum(item) for item in zip(*items)] for items in zip(*data)]
[[54, 40, 50, 50, 200], [20, 30, 75, 90, 180]]

答案 1 :(得分:2)

如果您使用Numpy,这会容易得多:

import numpy as np

data = [[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]],
       [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]],
       [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]]

a = np.array(data)
print a.sum(axis=0)

输出:

[[ 54,  40,  50,  50, 200],
 [ 20,  30,  75,  90, 180]]

类似地:

In [5]: a.sum(axis=1)
Out[5]:
array([[  6,  19,  55,  73, 181],
       [ 25,  11,  35,  27,  89],
       [ 43,  40,  35,  40, 110]])

In [6]: a.sum(axis=2)
Out[6]:
array([[169, 165],
       [121,  66],
       [104, 164]])

In [7]: a.sum()
Out[7]: 789

答案 2 :(得分:1)

您也可以使用map()

a = [[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]]
b = [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]]
c = [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]
results = []
for i in range(0, max(len(a), len(b), len(c))):
    results.append(map(lambda x, y, z: x + y + z, a[i], b[i], c[i]))

for result in results:
    for i in result:
        print(i)

但这是不必要的长时间,@ thefourtheye的回答更好。