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)?
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
The shortest solution I can imagine.
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
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))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.