Python函数,可以横向嵌套列表并打印出每个元素

时间:2013-08-10 04:26:04

标签: python list function nested

例如,如果列表[[['a', 'b', 'c'], ['d']],[['e'], ['f'], ['g']]],则该函数应打印出'a' 'b' 'c' ...等。在单独的行上。它需要能够对列表中的任何变化执行此操作。

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])

我的代码似乎无法正常工作,我知道我遗漏了很多必要的功能。任何建议都会非常有用

4 个答案:

答案 0 :(得分:3)

您首先要将列表展平:

>>> 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 :(得分:0)

这是一个递归功能。

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)

答案 2 :(得分:0)

如果可以有任意数量的嵌套子列表,那么对于递归函数来说这是一个很好的工作 - 基本上,编写一个函数,比如printNestedList如果参数不是列表则打印出参数,或者如果参数是列表,则在该列表的每个元素上调用printNestedList

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)

输出:

a
b
c
d
e
f
g

答案 3 :(得分:0)

import compiler

for x in compiler.ast.flatten(my_list):
     print x