[英]How do I convert a nested tuple of tuples and lists to lists of lists in Python?
我有一個包含列表和更多元組的元組。 我需要將它轉換為具有相同結構的嵌套列表。 例如,我想將(1,2,[3,(4,5)])
為[1,2,[3,[4,5]]]
。
我該怎么做(在Python中)?
def listit(t):
return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
我能想象的最短的解決方案。
作為一個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
我們可以(ab)使用json.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()會返回一個生成器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.