0

For example if have the list [[['a', 'b', 'c'], ['d']],[['e'], ['f'], ['g']]] the function should print out 'a' 'b' 'c' ...ect. on separate lines.It needs to be able to do this for any variation in the list.

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

My code doesnt seem to work, I know I am missing alot of whats needed for the neccesary function. Any suggestions would be very helpful

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Zaid Haddadin
  • 31
  • 1
  • 2

4 Answers4

3

You'll want to first flatten the list:

>>> 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
TerryA
  • 58,805
  • 11
  • 114
  • 143
0

Here's a recursive function that will do it.

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)
bravenewdude
  • 101
  • 3
0

If there can be any number of nested sublists, then this is a great job for a recursive function - basically, write a function, say printNestedList that prints out the argument if the argument is not a list, or if the argument is a list, call printNestedList on each element of that list.

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)

output:

a
b
c
d
e
f
g
Brionius
  • 13,858
  • 3
  • 38
  • 49
0
import compiler

for x in compiler.ast.flatten(my_list):
     print x
Nishant
  • 153
  • 1
  • 1
  • 8
Toni V
  • 41
  • 2