Skip to content Skip to sidebar Skip to footer

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 tw

Solution 1:

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.

Solution 2:

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

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

Solution 3:

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

Solution 4:

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

Solution 5:

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

classMyList(list):
    def__init__(self, *args):
        list.__init__(self, list(args))

    def__str__(self):
        return'---'.join(self)

classMyDict(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.

Post a Comment for "Best Way To Print List Output In Python"