KishB87
KishB87

Reputation: 303

Combining every two tuples within a list in Python

In a list of tuples, I'm trying to convert every consecutive pair to its sum.

E.g.,

[(t1, ), (t2, ), (t3, ), (t4, )] --> [(t1, t2) + (t3, t4)] 

How can this be done?


Example:

 a = [(119, 'Bob', 1L, 1L), (116, 'Twilight Sparkle', 1L, 1L), (117, 'Fluttershy', 0L, 1L), (118, 'Applejack', 0L, 1L)]

Then the output should be:

 [(119, 'Bob', 1L, 1L, 116, 'Twilight Sparkle', 1L, 1L), (117, 'Fluttershy', 0L, 1L, 118, 'Applejack', 0L, 1L)]

Upvotes: 0

Views: 42

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76316

Say the list is:

a = [(1, 2), (3, 4), (5, 6), (7, 8)]

Then using itertools.izip (for Python2.7),

import itertools

you can use:

>> [aa + bb for (aa, bb) in itertools.izip(a[::2], a[1::2])]

[(1, 2, 3, 4), (5, 6, 7, 8)]

Upvotes: 2

Related Questions