2

リストとその他のタプルを含むタプルがあります。同じ構造のネストされたリストに変換する必要があります。たとえば、に変換(1,2,[3,(4,5)])し たい[1,2,[3,[4,5]]]

これを行うにはどうすればよいですか (Python で)?

4

4 に答える 4

20
def listit(t):
    return list(map(listit, t)) if isinstance(t, (list, tuple)) else t

私が想像できる最短の解決策。

于 2009-06-18T19:19:02.133 に答える
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]]]

または、1つのライナーが好きな場合:

def f(t):
    return [f(i) for i in t] if isinstance(t, (list, tuple)) else t
于 2009-06-18T18:48:36.367 に答える
2

Python コレクションを JSON リストに変換しjson.loadsながら、常に JSON リストの Python リストを生成するという事実を (ab) 使用できます。json.dumps

import json

def nested_list(nested_collection):
    return json.loads(json.dumps(nested_collection))
于 2016-03-30T11:50:23.603 に答える
0

これは私が思いついたものですが、他の方が好きです。

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 では機能しないことがわかります。

于 2009-07-31T01:50:40.920 に答える