リストとその他のタプルを含むタプルがあります。同じ構造のネストされたリストに変換する必要があります。たとえば、に変換(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]]]
または、1つのライナーが好きな場合:
def f(t):
return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
Python コレクションを JSON リストに変換しjson.loads
ながら、常に JSON リストの Python リストを生成するという事実を (ab) 使用できます。json.dumps
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のコメントから、 map() がジェネレーターを返すため、これは Python 3.x では機能しないことがわかります。