简体   繁体   中英

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.

Eg,

[(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)]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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