如何将Python中的嵌套元组和列表转换为列表的列表?
我有一个包含列表和其他元组的元组。我需要把它转换成嵌套的列表,保持相同的结构。比如,我想把 (1,2,[3,(4,5)])
转换成 [1,2,[3,[4,5]]]
。
我该怎么做呢(用Python)?
4 个回答
2
我们可以利用一个特点,就是 json.loads
这个函数在处理 JSON 列表时,总是会生成 Python 的列表,而 json.dumps
则会把任何 Python 的集合转换成 JSON 列表:
import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
8
作为一个刚接触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]]]
或者,如果你喜欢一行代码的写法:
def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
22
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
我能想到的最简单的解决办法。