我有一个包含列表和元组的元组。我需要将它转换为具有相同结构的嵌套列表。例如,我想将
在Python中,我该如何做到这一点?
(1,2,[3,(4,5)])
转换为 [1,2,[3,[4,5]]]
。在Python中,我该如何做到这一点?
(1,2,[3,(4,5)])
转换为 [1,2,[3,[4,5]]]
。def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
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
hasattr(t,'iter')
太多余了,因为字符串也是可迭代的(通常情况下你不想将它们转换为字符列表)。 - bernard paulusjson.loads
总是将JSON列表转换为Python列表,而json.dumps
将任何Python集合转换为JSON列表:import json
def nested_list(nested_collection):
return json.loads(json.dumps(nested_collection))
这是我想到的,但我喜欢其他的更好。
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)
我看到aztek的答案可以缩短为:
def deep_list(x):
return map(deep_list, x) if isinstance(x, (list, tuple)) else x
更新:但是现在我从DasIch的评论中看到,在Python 3.x中这不起作用,因为map()返回一个生成器。