-1

I'm trying to write a function that will basically print:

file1

file2

file3

file4

file5

file6

file7

When I enter:

C = [['file1', [['file2']], ['file3', 'file4', 'file5']], 'file6', ['file7']]

It's supposed to be like a directory.

Here is my code:

def tree_traverse(directory) :

    list1 = list(directory)
    for it in list1 :
        if it == 'Cc' :
            del(list1[:(list1[it]+3)])
    for item in directory :
        print(item)

Whenever I enter the input above, I get an error saying C is an unexpected argument. Also, when I enter the above input without the "C = ", it just prints it like I entered it. I'm quite lost at what to do.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    ... An unexpected argument to *what*? – Ignacio Vazquez-Abrams Aug 08 '13 at 01:57
  • @Ignacio this is the error I get: Traceback (most recent call last): File "", line 1, in tree_traverse(C = [['file1', [['file2']], ['file3', 'file4', 'file5']], 'file6', ['file7']]) TypeError: tree_traverse() got an unexpected keyword argument 'C' – Preston May Aug 08 '13 at 01:58
  • 1
    Related : [Flatten (an irregular) list of lists in Python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) – Ashwini Chaudhary Aug 08 '13 at 01:59

3 Answers3

1

This flattens the list as you want.

C = [['file1', [['file2']], ['file3', 'file4', 'file5']], 'file6', ['file7']]

def getFiles(container):
    for f in container:
        if isinstance(f, list):
            for fArray in getFiles(f):
                yield fArray
        else:
            yield f

print "".join("%s\n" %f for f in list(getFiles(C)))
0

The function has no argument called C therefore you cannot pass it a keyword argument called C. Either use directory=... instead or pass it the object as a normal argument.

C = ...
tree_traverse(C)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Using a recursive method (that should work for an indefinite number of layers):

def print_list(obj, final_string=""):
    if isinstance(obj, list):
        for itm in obj:
            final_string = print_list(itm, final_string)
        return final_string
    else:
        return final_string + "\n" + obj

print print_list(c)
scohe001
  • 15,110
  • 2
  • 31
  • 51