简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM