Ibe
Ibe

Reputation: 6035

How to add paired values in sub-lists separately?

I have a list of lists:

a = [[2,3,4,5],[1,3,2,7]]

and I want to sum consecutive paired values in each sub-list separately to output:

[[5,9],[4,9]]

and using following but not getting as needed:

b = [sum(a[i:i+2]) for i in xrange(0,len(a),2)]

Any suggestions would be appreciative.

Upvotes: 0

Views: 27

Answers (1)

falsetru
falsetru

Reputation: 369314

Use nested list comprehension.

>>> a = [[2,3,4,5],[1,3,2,7]]
>>> [[sum(sublist[i:i+2]) for i in xrange(0,len(sublist),2)] for sublist in a]
[[5, 9], [4, 9]]

Equivalent, easier to read version using a function:

>>> def paired_sum(a):
...     return [sum(a[i:i+2]) for i in xrange(0,len(a),2)]
... 
>>> [paired_sum(sublist) for sublist in a]
[[5, 9], [4, 9]]
>>> map(paired_sum, a)
[[5, 9], [4, 9]]

Upvotes: 1

Related Questions