Search code examples
pythonlistpython-2.x

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) ]

`

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)]