Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nested tuples to nested lists

I/P - (('1', (('2355', '5'), 'F')),
       ('1', (('2300', '4'), 'M')),
       ('1', (('2400', '5'), 'F')))
O/P - [['1','2355','5','F'],
       ['1','2300','4','M'],
       ['1','2400','5','F']]

I am able to get the first element but the other elements are still extracted as a tuple whereas I want all of them to come out as part of a list. Basically, I want every element to come out individually as part of a list.

like image 795
rAmAnA Avatar asked Feb 11 '26 21:02

rAmAnA


1 Answers

in 3.3+ there is a recursive idiom that can be modified to flatten nested tuples of 'any' depth (see: system recursion limit)

def yielder(x):
    for y in x:
        if isinstance(y, tuple):
            yield from yielder(y)
        else:
            yield y

which can then be used in a list comprehension

[[*yielder(e)] for e in IP]
Out[48]: [['1', '2355', '5', 'F'], ['1', '2300', '4', 'M'], ['1', '2400', '5', 'F']]

I found the above by searching for 'python flatten', in the comments to https://jugad2.blogspot.in/2014/10/flattening-arbitrarily-nested-list-in.html

for 2/7 http://joedicastro.com/aplanar-listas-en-python.html has recipes, I modded:

def flat_slice ( lst ):
    lst = list ( lst )
    for i , _ in enumerate ( lst ):
        while ( hasattr ( lst [ i ], "__iter__" ) and not isinstance ( lst [ i ], basestring )):
             lst [ i : i + 1 ] = lst [ i ]
    return lst

(I had to change basestring to str for 3+)

and it ran with the same result

[[*flat_slice(e)] for e in IP]
Out[66]: [['1', '2355', '5', 'F'], ['1', '2300', '4', 'M'], ['1', '2400', '5', 'F']]
like image 89
f5r5e5d Avatar answered Feb 14 '26 09:02

f5r5e5d



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!