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 fixed the two above lists so that I can match their index value 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 above mylist using

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

As a result, this result was my desired output .

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

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

+4
source share
5 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 will get something β€œbetter” anyway.

+8
source

The next for loop combines print and concatenate operations on one line.

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

It may not be as readable as a full-cycle 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 
+3
source

Here is another way to achieve the result. This is shorter, but I'm not sure if this is more readable:

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

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

If you combine this with mgilson's suggestion to use a dictionary (I would even suggest 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 to need print details for this data.

+2
source

Source: https://habr.com/ru/post/1414443/


All Articles