Reputation: 77
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
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
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