Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sort without lambda expressions

I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me.

I have a list of numbers, e.g., x = [12, 101, 4, 56, ...]

I have a separate list of indices: y = range(len(x))

I want to sort y based on the values in x, and I do this:

y.sort(key=lambda a: x[a])

Is there a good way to do this without using lambda?

like image 554
gaefan Avatar asked Aug 04 '10 16:08

gaefan


1 Answers

You can use the __getitem__ method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function:

>>> x = [12, 101, 4, 56]
>>> y = range(len(x))
>>> sorted(y, key=x.__getitem__)
[2, 0, 3, 1]
like image 120
Dave Kirby Avatar answered Oct 08 '22 00:10

Dave Kirby