Reputation: 149404
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)?
Upvotes: 5
Views: 14271
Reputation: 9994
We can (ab)use the fact that json.loads
always produces Python lists for JSON lists, while json.dumps
turns any Python collection into a JSON list:
import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
Upvotes: 2
Reputation: 149404
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.
Upvotes: 0
Reputation: 1431
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
The shortest solution I can imagine.
Upvotes: 22
Reputation: 2058
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
Upvotes: 9