简体   繁体   English

Python中具有不同长度的列表列表中的元素总和

[英]Sum of elements in a list of lists with varying lengths in Python

I am trying to calculate the sum of elements in a list of lists. 我试图计算列表列表中的元素总和。 I have no trouble in computing the sum if the lists within the main list all have the same size, like below: 如果主列表中的列表都具有相同的大小,我可以毫不费力地计算总和,如下所示:

a = [[4], [8], [15]]
total = [sum(i) for i in zip(*a)]

result: 结果:

total = [27]     #(4 + 8 + 15) = 27, GOOD!!!

however there is a chance that I may have a list with a different size within the main list, such as: 但是我可能在主列表中有一个不同大小的列表,例如:

a = [[3], [4, 6], [10]]

expected result: 预期结果:

total = [17, 19]     #(3 + 4 + 10) = 17, (3 + 6 + 10) = 19

I got stuck here, obviously my solution for the lists of equal sizes does not work. 我被困在这里,显然我的相同大小的列表的解决方案不起作用。 What would be the best way to get the result the way I defined? 以我定义的方式获得结果的最佳方法是什么? My intuition was figuring out the list with the maximum length, then expanding other lists to that length with adding zeros, and finally computing the sums separately. 我的直觉是找出具有最大长度的列表,然后通过添加零将其他列表扩展到该长度,最后分别计算总和。 This sounds like an ugly solution though, and I wonder if there is there a quick and more elegant way to do this. 这听起来像一个丑陋的解决方案,我想知道是否有一个快速,更优雅的方式来做到这一点。

Thanks! 谢谢!

EDIT: Should have explained it better. 编辑:应该更好地解释它。 I got confused a bit too... Here below are better examples: 我也有点困惑......以下是更好的例子:

The number of elements in the lists within the list a never exceeds 2. Examples: 列表内的列表元素的数量a永远不会超过2。实施例:

a = [[1], [10], [5]] #Expected result: [16] (1+10+5)

a = [[1, 10], [3], [4]] #Expected result: [8, 17] (1+3+4, 10+3+4)

a = [[1, 10], [3], [2, 8]] #Expected result: [6, 12, 15, 21] (1+3+2, 1+3+8, 10+3+2, 10+3+8)

EDIT2: Accepted answer computes the correct results independent of the list sizes. EDIT2:接受的答案计算独立于列表大小的正确结果。

Wild guess: you want every possible sum, ie the sums you get from taking every possible selection of elements from the sublists? 狂野猜测:你想要所有可能的总和,即你从子列表中获取每一个可能选择的元素得到的总和?

>>> from itertools import product
>>> a = [[4], [8], [15]]
>>> [sum(p) for p in product(*a)]
[27]
>>> a = [[3], [4, 6], [10]]
>>> [sum(p) for p in product(*a)]
[17, 19]

One way to check this interpretation is to see whether you like the answer it gives for the test in the comments: 检查此解释的一种方法是查看您是否喜欢在评论中为测试提供的答案:

>>> a = [[1,2], [3,4,5], [6,7,8,9]] # Tim Pietzcker's example
>>> [sum(p) for p in product(*a)]
[10, 11, 12, 13, 11, 12, 13, 14, 12, 13, 14, 15, 11, 12, 13, 14, 12, 13, 14, 15, 13, 14, 15, 16]

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

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