python - changing from tuple to list and vice versa -
how change [('a', 1), ('c', 3), ('b', 2)]
['a',1,'c',3,'b',2]
, vice versa? thanks
going in first direction [('a', 1), ('c', 3), ('b', 2)]
['a',1,'c',3,'b',2]
flattening list. taking accepted answer there , modifying example:
>>> l = [('a', 1), ('c', 3), ('b', 2)] >>> list(itertools.chain(*l)) ['a', 1, 'c', 3, 'b', 2]
this uses itertools.chain
nice tool itertools
flattens sequences quite nicely.
going opposite way zipping:
>>> l = ['a', 1, 'c', 3, 'b', 2] >>> zip(l[0::2], l[1::2]) [('a', 1), ('c', 3), ('b', 2)]
zip
takes 2 lists , combines list 1's first element list 2's first element in tuple, , on down lengths of list. in one, take even-indexed elements our first list (l[0::2]
), , odd-indexed elements our second (l[1::2]
)
Comments
Post a Comment