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!
You could try this:
This uses a combination of
zipand*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 the case of lists that are of unequal length, you can use
itertools.izip_longestwith afillvalueof0– this basically fills missing indices with0, allowing you to sum all ‘columns’:In this case, here is what iterating over
izip_longestwould look like: