Python Convert List Of Nested Tuples To List Of Tuples
I have a list of nested tuples as [(('p1', 'p2'), ('m1',)), (('p2', 'p1'), ('m1',))] How can i convert it into list of tuples as [('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')] without
Solution 1:
You can do with itertools.chain,
In[91]: fromitertoolsimportchainIn[92]: [tuple(chain(*item)) for item in a]Out[92]: [('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]Solution 2:
You can use list comprehension with a generator as element in the tuple(..) constructor:
[tuple(x forelemin row forxin elem) forrowin data]The code fragment in boldface is a generator: for every row (i.e. (('p1', 'p2'), ('m1',))) it yield the elements that are two levels deep so: p1, p2 and m1. These are converted into a tuple.
Or you can use itertools:
from itertools import chain
[tuple(chain(*row)) for row in data]This generates:
>>> data = [(('p1', 'p2'), ('m1',)), (('p2', 'p1'), ('m1',))]
>>> [tuple(x for elem in row for x in elem) for row in data]
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]
>>> [tuple(chain(*row)) for row in data]
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]
You can also use itertools.starmap(..) and list(..) to remove the list comprehension:
from itertools import chain, starmap
list(map(tuple,starmap(chain,data)))Which gives:
>>> list(map(tuple,starmap(chain,data)))
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]
Note that although you do not write a for loop yourself, of course there is still a loop mechanism in place at the list comprehension or map(..) and starmap(..) functions.
Post a Comment for "Python Convert List Of Nested Tuples To List Of Tuples"