简体   繁体   English

如何使用for循环查找列表列表的总和

[英]How to find sum of list of lists using for-loop

prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]

I want to create a sum list that will add every value from every list of lists with each corresponding ones. 我想创建一个总和列表,它将从每个列表列表中添加每个对应的值。 To be accurate i want: 为了准确我想:

sum = [[0+0, 4+0.27, 6+6, 5+7, 45+32, 1+3], [2+0.1, 3+0.39, 5+0, 6+0, 7+0, 1+0]]

I want to do it with a for loop so that i can use the same algorithm for bigger list of lists.I made the example simple to make it more readable. 我想用for循环这样做,这样我就可以使用相同的算法来获得更大的list列表。我使这个例子变得简单,使它更具可读性。 I have python 2.7 . 我有python 2.7。

Use the zip() function to pair up elements from 2 or more lists, then use sum() to add up the combined values: 使用zip()函数配对2个或更多列表中的元素,然后使用sum()来组合组合值:

summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]

Note the zip(*prefer_indic) call, which transposes your matrix so that you pair up the 'columns' of your nested lists, not the rows. 请注意zip(*prefer_indic)调用,该调用会转置矩阵,以便您对嵌套列表的“列”进行配对,而不是对。

If your lists are larger, it may be beneficial to using the iterative version of zip ; 如果您的列表较大,则使用zip迭代版本可能是有益 ; use the future_builtins.zip() location and your code is automatically forward-compatible with Python 3: 使用future_builtins.zip()位置 ,您的代码自动向前兼容Python 3:

try:
    from future_builtins import zip
except ImportError:
    # Python 3

summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]

Demo: 演示:

>>> from future_builtins import zip
>>> prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]
>>> [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]
[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]]

I would define a function that adds two lists, then use a list comprehension to compute your desired result: 我将定义一个添加两个列表的函数,然后使用列表推导来计算您想要的结果:

def add_lists(a, b):
    return list(x+y for x, y in zip(a, b))

s = list(add_lists(*l) for l in zip(*prefer_indic))

For you example 对你而言

prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]

the result will be 结果将是

[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM