Mikasa Ackerman
Mikasa Ackerman

Reputation: 77

Printing nested list as string for display

I have this code:

data = [["apple", 2], ["cake", 7], ["chocolate", 7], ["grapes", 6]]

I want to nicely put it on display when running my code so that you won't see the speech marks,or square brackets, have it displayed like so:

apple, 2
cake, 7
chocolate, 7
grapes, 6

I looked on this site to help me:

http://www.decalage.info/en/python/print_list

However they said to use print("\n".join), which only works if values in a list are all strings.

How could I solve this problem?

Upvotes: 0

Views: 2043

Answers (2)

Grysik
Grysik

Reputation: 846

Or you can do it in very complicated way, so each nested list would be printed in it's own line, and each nested element that is not also. Something like "ducktyping":

def printRecursively(toPrint):
    try:
        #if toPrint and nested elements are iterables
        if toPrint.__iter__() and toPrint[0].__iter__():
            for el in toPrint:
                printRecursively(el)
    except AttributeError:
        #toPrint or nested element is not iterable
        try:
            if toPrint.__iter__():
                print ", ".join([str(listEl) for listEl in toPrint])
        #toPrint is not iterable
        except AttributeError:
            print toPrint
data = [["apple", 2], ["cake", 7], [["chocolate", 5],['peanuts', 7]], ["grapes", 6], 5, 6, 'xx']
printRecursively(data)

Hope you like it :)

Upvotes: 0

jedwards
jedwards

Reputation: 30210

In general, there are things like pprint which will give you output to help you understand the structure of objects.

But for your specific format, you can get that list with:

data=[["apple",2],["cake",7],["chocolate",7],["grapes",6]]

for (s,n) in data: print("%s, %d" % (s,n))
# or, an alternative syntax that might help if you have many arguments
for e in data: print("%s, %d" % tuple(e))

Both output:

apple, 2
cake, 7
chocolate, 7
grapes, 6

Upvotes: 3

Related Questions