Dar*_*zer 2 python tuples list
我有一个包含列表和更多元组的元组.我需要将它转换为具有相同结构的嵌套列表.例如,我想转换(1,2,[3,(4,5)])为 [1,2,[3,[4,5]]].
我该怎么做(在Python中)?
azt*_*tek 16
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
Run Code Online (Sandbox Code Playgroud)
我能想象的最短的解决方案.
作为一个python新手,我会尝试这个
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]]]
Run Code Online (Sandbox Code Playgroud)
或者,如果您喜欢一个衬垫:
def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
Run Code Online (Sandbox Code Playgroud)