20

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.

3 Answers 3

24

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Python 3 note: zip returns an iterator in Python 3, use list to see its content, zipped = list(zip(filename, human_rating, …))
@David Wolever very nice solution.
In case you're getting 'zip' object has no attribute 'sort' error, use sorted(zipped) as @jochen-ritzel mentioned in his answer.
12

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)

2 Comments

Nice and compact solution! the problem is that it returns tuples not lists.
@ParisaKhateri Combine it with map if you need lists: l1, l2, l3, ... = map(list, zip(*sorted(zip(l1, l2, l3, ...))))
2

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

for ... in sorted(zip( ... )):
    print " ... "

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.