Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine list elements

Tags:

python

How can I merge/combine two or three elements of a list. For instance, if there are two elements, the list 'l'

l = [(a,b,c,d,e),(1,2,3,4,5)]

is merged into

[(a,1),(b,2),(c,3),(d,4),(e,5)]

however if there are three elements

l = [(a,b,c,d,e),(1,2,3,4,5),(I,II,II,IV,V)] 

the list is converted into

[(a,1,I),(b,2,II),(c,3,III),(d,4,Iv),(e,5,V)]

Many thanks in advance.

like image 850
DGT Avatar asked Mar 16 '26 23:03

DGT


1 Answers

Use zip:

l = [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, 5)]
print zip(*l)

Result:

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
like image 69
Mark Byers Avatar answered Mar 18 '26 13:03

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!