RanRag
RanRag

Reputation: 49567

Best way to print list output in python

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.

Upvotes: 4

Views: 13216

Answers (5)

garnertb
garnertb

Reputation: 9584

The following for loop will combine both the print and join operations into one line.

 for item in zip(list1,list2):
     print '{0}\n{1}'.format(item[0],'---'.join(item[1]))

Upvotes: 4

Anthon
Anthon

Reputation: 76614

What you might consider clean, but I do not, is that your the rest of your program needs to now the structure of your data and how to print it. IMHO that should be contained in the class of the data, so you can just do print mylist and get the desired result.

If you combine that with mgilson's suggestion to use a dictionary ( I would even suggest an OrderedDict) I would do something like this:

from collections import OrderedDict

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, list(args))

    def __str__(self):
        return '---'.join(self)

class MyDict(OrderedDict):
    def __str__(self):
        ret_val = []
        for k, v in self.iteritems():
            ret_val.extend((k, str(v)))
        return '\n'.join(ret_val)

mydata = MyDict([
    ('a', MyList("1","2","3","4")),
    ('b', MyList("5","6","7","8")),
    ('c', MyList("9","10","11","12")),
])

print mydata

without requiring the rest of the program needing to know the details of printing this data.

Upvotes: 1

Jesse
Jesse

Reputation: 21

Here's another way to achieve the result. It's shorter, but I'm not sure it's more readable:

print '\n'.join([x1 + '\n' + '---'.join(x2) for x1,x2 in zip(list1,list2)])

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

It may not be quite as readable as a full loop solution, but the following is still readable and shorter:

>>> zipped = zip(list1, list2) 
>>> print '\n'.join(label + '\n' + '---'.join(vals) for label, vals in zipped)
a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

Upvotes: 2

Danica
Danica

Reputation: 28846

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.

Upvotes: 7

Related Questions