开发者

Traversing a "list" tree and get the type(item) list with same structure in python? [duplicate]

开发者 https://www.devze.com 2023-03-12 03:36 出处:网络
This question already has answers here: Iterating through list of list in Python (11 answers) Closed 7 years ago.
This question already has answers here: Iterating through list of list in Python (11 answers) Closed 7 years ago.

"tree" structured list:

[(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1")))]  # may be more complex
  1. How to traversing it and print each item - I means the 1 and the "1"?

  2. How to generate type list with same structure?

    [('int','int',('int','int',('int','str'))),('int','int','int'),('int',),'int',('int',('int',('str')))]

    the 'int', 'str' here should be output of type(1) and type("s") as it can not been displayed on the question

开发者_开发知识库

Thanks!


You can create a generator that will traverse the tree for you for (1).

def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

Here is one possible approach to (2).

def tree_map(f, o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        return type(o)(tree_map(f, value, tree_types) for value in o)
    else:
        return f(o)

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print tree_map(lambda o: type(o).__name__, data)
# prints [('int', 'int', ('int', 'int', ('int', 'str'))), ('int', 'int', 'int'), ('int',), 'int', ('int', ('int', ('str',)))]


You can walk any tree-like structure easily using recursion. Just define a function that would look at all it's children. Though traditionally, each child is itself a tree however in your case, it might be. So I guess you could do something like this:

def traverseit(tree):
    if hasattr(tree, '__iter__'):
        for subtree in tree:
            traverseit(subtree)
    else:
        print(tree)


For your second question, assuming you just want to get a new "tree" that replaces the "nodes" with their types, simple:

def transformit(tree):
    nodetype = type(tree)
    if hasattr(tree, '__iter__'):
        return nodetype(transformit(subtree) for subtree in tree)
    else:
        return nodetype


for #2 you can use this recursive lamba function and use it in map

   f = lambda o: (isinstance(o, tuple) and  tuple(map(f, o))) or type(o).__name__
   map(f, [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1")))])

returns: [('int', 'int', ('int', 'int', ('int', 'str'))), ('int', 'int', 'int'), ('int',), 'int', ('int', ('int', 'str'))]

0

精彩评论

暂无评论...
验证码 换一张
取 消