Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

python - Sum of list of lists; returns sum list

Let data = [[3,7,2],[1,4,5],[9,8,7]]

Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length.

    print foo(data)

   [[3,7,2],
    [1,4,5],
    [9,8,7]]
    _______
 >>>[13,19,14]

How can I iterate over the list of lists without getting an index out of range error? Maybe lambda? Thanks!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try this:

In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]

In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]

This uses a combination of zip and * to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their 'original' position.

To hopefully make it a bit more clear, here is what happens when you iterate through zip(*l):

In [13]: for i in zip(*l):
   ....:     print i
   ....:     
   ....:     
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)

In the case of lists that are of unequal length, you can use itertools.izip_longest with a fillvalue of 0 - this basically fills missing indices with 0, allowing you to sum all 'columns':

In [1]: import itertools

In [2]: l = [[3,7,2],[1,4],[9,8,7,10]]

In [3]: [sum(i) for i in itertools.izip_longest(*l, fillvalue=0)]
Out[3]: [13, 19, 9, 10]

In this case, here is what iterating over izip_longest would look like:

In [4]: for i in itertools.izip_longest(*l, fillvalue=0):
   ...:     print i
   ...:     
(3, 1, 9)
(7, 4, 8)
(2, 0, 7)
(0, 0, 10)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...