I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert (1,2,[3,(4,5)])
to [1,2,[3,[4,5]]]
.
How do I do this (in Python)?
I have a tuple containing lists and more tuples. I need to convert it to nested lists with the same structure. For example, I want to convert (1,2,[3,(4,5)])
to [1,2,[3,[4,5]]]
.
How do I do this (in Python)?
As a python newbie I would try this
def f(t):
if type(t) == list or type(t) == tuple:
return [f(i) for i in t]
return t
t = (1,2,[3,(4,5)])
f(t)
>>> [1, 2, [3, [4, 5]]]
Or, if you like one liners:
def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
The shortest solution I can imagine.
This is what I had come up with, but I like the other's better.
def deep_list(x):
"""fully copies trees of tuples or lists to a tree of lists.
deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]
deep_list( (1,2,[3,(4,5)]) ) returns [1,2,[3,[4,5]]]"""
if not ( type(x) == type( () ) or type(x) == type( [] ) ):
return x
return map(deep_list,x)
I see aztek's answer can be shortened to:
def deep_list(x):
return map(deep_list, x) if isinstance(x, (list, tuple)) else x
Update: But now I see from DasIch's comment that this wouldn't work in Python 3.x since map() there returns a generator.