Python function which can transverse a nested list and print out each element
本问题已经有最佳答案,请猛点这里访问。
例如,如果有清单
1 2 3 4 5 6 7 | my_list = [[['a', 'b', 'c'], ['d']],[[[['e', ['f']]]]], ['g']] def input1(my_list): for i in range(0, len(my_list)): my_list2 = my_list[i] for i in range(0, len(my_list2)): print(my_list2[i]) |
我的代码似乎不起作用,我知道我遗漏了很多必要的功能所需要的东西。有什么建议会很有帮助的
您将首先要展平列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | >>> import collections >>> def flatten(l): ... for el in l: ... if isinstance(el, collections.Iterable) and not isinstance(el, basestring): ... for sub in flatten(el): ... yield sub ... else: ... yield el ... >>> L = [[['a', 'b', 'c'], ['d']],[['e'], ['f'], ['g']]] >>> for item in flatten(L): ... print item ... a b c d e f g |
1 2 3 4 | import compiler for x in compiler.ast.flatten(my_list): print x |
如果可以有任何数量的嵌套子列表,那么对于递归函数来说,这是一项很好的工作——基本上,编写一个函数,比如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | nl = [[['a', 'b', 'c'], ['d']],[['e'], ['f'], ['g']]] def printNestedList(nestedList): if len(nestedList) == 0: # nestedList must be an empty list, so don't do anyting. return if not isinstance(nestedList, list): # nestedList must not be a list, so print it out print nestedList else: # nestedList must be a list, so call nestedList on each element. for element in nestedList: printNestedList(element) printNestedList(nl) |
输出:
1 2 3 4 5 6 7 | a b c d e f g |
。
这里有一个递归函数可以做到这一点。
1 2 3 4 5 6 7 8 9 10 | def PrintStrings(L): if isinstance(L, basestring): print L else: for x in L: PrintStrings(x) l = [[['a', 'b', 'c'], ['d']],[['e'], ['f'], ['g']]] PrintStrings(l) |
号