0

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?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • 1
    This is a rather simple programming task and I will give only basic pointers to a solution: iterate over the list, print the two values in each item separately! – Klaus D. Mar 17 '15 at 08:29

2 Answers2

3

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
jedwards
  • 29,432
  • 3
  • 65
  • 92
  • @PeterWood, thanks! [Just hit it not too long ago (comments)](http://stackoverflow.com/a/29093043/736937) – jedwards Mar 17 '15 at 09:15
0

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

Grysik
  • 807
  • 7
  • 16