0

Suppose a list of lists, something like this:

lists=[[3,2,1,4],[6,4,2,8],[9,6,3,12]]

If I want to sort by lists[0]it should be sorted like this:

lists=[[1,2,3,4],[2,4,6,8],[3,6,9,12]] #can be another variable

Having a list of three lists:

list1,list2,list3=(list(t) for t in zip(*sorted(zip(lists[0], lists[1],lists[2]))))

But that is a specific solution, n lists inside a list could be more general.
The lists variable was created like this:

lists = [[] for x in xrange(n)]

And the values were appended on.

Actually all values are numeric (float or int), but this might explain it better.

lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]

I would like to know how to sort that and end up with this:

[[1,2,3,4],["one","two","three","four"],["uno","dos","tres","cuatro"]]
1
  • 1
    Use * notation on the list of lists: zip(*lists). Commented Apr 21, 2013 at 20:54

1 Answer 1

4

This might be the unlikely case where it's best to use a Schwartzian transform

>>> lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]
>>> [[x for i, x in sorted(zip(lists[0], sublist))] for sublist in lists]
[[1, 2, 3, 4], ['one', 'two', 'three', 'four'], ['uno', 'dos', 'tres', 'cuatro']]
Sign up to request clarification or add additional context in comments.

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.