0

例如,如果有列表[[['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

4 回答 4

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
于 2013-08-10T04:35:10.563 回答
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)
于 2013-08-10T04:43:12.497 回答
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
于 2013-08-10T04:43:28.370 回答
0
import compiler

for x in compiler.ast.flatten(my_list):
     print x
于 2013-08-10T10:25:15.063 回答