Alejandro Zuleta
Alejandro Zuleta

Reputation: 3

Python sort lists with lists inside

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"]]

Upvotes: 0

Views: 1200

Answers (1)

jamylak
jamylak

Reputation: 133564

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']]

Upvotes: 4

Related Questions