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

Answers


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

Need Your Help

Reading text files

c++ file-io input

I'm trying to find out what is the best way to read large text (at least 5 mb) files in C++, considering speed and efficiency. Any preferred class or function to use and why?

How to execute sql-script file in java?

java sql-scripts

I want to execute an SQL script file in Java without reading all file content into a big query and executing it. Is there any standard way?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.