Sort multiple lists based on one list in python

I print multiple lists, but the values ​​are not sorted.

for f, h, u, ue, b, be, p, pe, m, me in zip(filename, human_rating, rating_unigram, percentage_error_unigram, rating_bigram, percentage_error_bigram, rating_pos, percentage_error_pos, machine_rating, percentage_error_machine_rating): print "{:>6s}{:>5.1f}{:>7.2f}{:>8.2f} {:>7.2f} {:>7.2f} {:>7.2f} {:>8.2f} {:>7.2f} {:>8.2f}".format(f,h,u,ue,b,be,p,pe,m,me) 

What is the best way to sort all of these lists based on the values ​​in 'filename'?

So if:

 filename = ['f3','f1','f2'] human_rating = ['1','2','3'] etc. 

Then the sorting will return:

 filename = ['f1','f2','f3'] human_rating = ['2','3','1'] etc. 
+8
python list
source share
3 answers

I would then black out sort:

 zipped = zip(filename, human_rating, …) zipped.sort() for row in zipped: print "{:>6s}{:>5.1f}…".format(*row) 

If you really want to return individual lists, I would sort them as described above and then unzip them:

 filename, human_rating, … = zip(*zipped) 
+8
source share

How about this: zip into a list of tuples, sort the list of tuples, then "unzip"?

 l = zip(filename, human_rating, ...) l.sort() # 'unzip' filename, human_rating ... = zip(*l) 

Or in one line:

 filename, human_rating, ... = zip(*sorted(zip(filename, human_rating, ...))) 

Run Example:

 foo = ["c", "b", "a"] bar = [1, 2, 3] foo, bar = zip(*sorted(zip(foo, bar))) print foo, "|", bar # prints ('a', 'b', 'c') | (3, 2, 1) 
+2
source share

zip returns a list of tuples that you can sort by their first value. So:

 for ... in sorted(zip( ... )): print " ... " 
0
source share

All Articles