Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting multiple lists based on a single list in python

Tags:

python

list

I'm printing a few 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's 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 sorting would return:

filename = ['f1','f2','f3']
human_rating = ['2','3','1']
etc.
like image 633
Zach Avatar asked Jul 22 '12 16:07

Zach


People also ask

How do you sort 3 lists in Python?

sort() Syntax The syntax of the sort() method is: list.sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.

Can you sort a list of lists in Python?

You can sort a list in Python using the sort() method. The method accepts two optional arguments: reverse : which sorts the list in the reverse order (descending) if True or in the regular order (ascending) if False (which it is by default)

How do you sort a list like another list in Python?

sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.

Can we sort nested list in Python?

There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.


2 Answers

I would zip then sort:

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

If you really want to get the individual lists back, I would sort them as above, then unzip them:

filename, human_rating, … = zip(*zipped)
like image 173
David Wolever Avatar answered Sep 28 '22 05:09

David Wolever


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, ...)))

Sample run:

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)
like image 25
orip Avatar answered Sep 28 '22 05:09

orip