Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to print list output in python

Tags:

python

list

I have a list and a list of list like this

>>> list2 = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"]]
>>> list1 = ["a","b","c"]

I zipped the above two list so that i can match their value index by index.

>>> mylist = zip(list1,list2)
>>> mylist
[('a', ['1', '2', '3', '4']), ('b', ['5', '6', '7', '8']), ('c', ['9', '10', '11', '12'])]

Now I tried to print the output of above mylist using

>>> for item in mylist:
...     print item[0]
...     print "---".join(item[1])
...

It resulted in this output which is my desired output.

a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

Now, my question is there a more cleaner and better way to achieve my desired output or this is the best(short and more readable) possible way.

like image 385
RanRag Avatar asked Dec 01 '22 06:12

RanRag


1 Answers

Well, you could avoid some temporary variables and use a nicer loop:

for label, vals in zip(list1, list2):
    print label
    print '---'.join(vals)

I don't think you're going to get anything fundamentally "better," though.

like image 121
Danica Avatar answered Dec 15 '22 22:12

Danica