Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python convert different depth list of tuples to flatten list of tuples

I have a tuple of characters like such:

p= [((4.0, 4.0), '->', ((4, 2), (4, 8)), ((2, 2), (5, 5))), ((4.0, 7.0), '->', ((4, 2), (4, 8)), ((5, 6), (3, 8)))]`

How do I convert it to a tupple so that it is like:

p = [(4.0,4.0), (4, 2), (4, 8), (2, 2), (5, 5),(4.0, 7.0), (4, 2), (4, 8), (5, 6), (3, 8) ]

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was trying this way but output is coming with double bracket for some

res = []
for tup in p:
    for sub_tup in tup:
        print sub_tup, type(sub_tup)
        if type(sub_tup) == tuple:
            res.append(sub_tup)
            
print(res)

Output

  [(4.0, 4.0), ((4, 2), (4, 8)), ((2, 2), (5, 5)), (4.0, 7.0), ((4, 2), (4, 8)), ((5, 6), (3, 8))] 

>Solution :

You can write a recursive solution like the below:

p = [((4.0, 4.0), '->', ((4, 2), (4, 8)), ((2, 2), (5, 5))), ((4.0, 7.0), '->', ((4, 2), (4, 8)), ((5, 6), (3, 8)))]

def rec_flat(tpl, result):
    for t in tpl:
        if type(t[0]) not in [str, tuple]:
            result.append(t)
        elif isinstance(t, tuple):
            rec_flat(t, result)



result = []
rec_flat(p, result)
print(result)

Output:

[(4.0, 4.0), (4, 2), (4, 8), (2, 2), (5, 5), (4.0, 7.0), (4, 2), (4, 8), (5, 6), (3, 8)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading