Sorting by arbitrary lambda

PythonSorting

Python Problem Overview


How can I sort a list by a key described by an arbitrary function? For example, if I have:

mylist = [["quux", 1, "a"], ["bar", 0, "b"]]

I'd like to sort "mylist" by the second element of each member, e.g.

sort(mylist, key=lambda x: x[1])

how can I do this?

Python Solutions


Solution 1 - Python

You basically have it already:

>>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
>>> mylist.sort(key=lambda x: x[1])
>>> print mylist

gives:

[['bar', 0, 'b'], ['quux', 1, 'a']]

That will sort mylist in place.

[this para edited thanks to @Daniel's correction.] sorted will return a new list that is sorted rather than actually changing the input, as described in http://wiki.python.org/moin/HowTo/Sorting/.

Solution 2 - Python

You have two options, very close to what you described, actually:

mylist.sort(key=lambda x: x[1]) # In place sort
new_list = sorted(mylist, key=lambda x: x[1])

Solution 3 - Python

This is such a common need that support for it has been added to the standard library, in the form of operator.itemgetter:

from operator import itemgetter
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
mylist.sort(key=itemgetter(1)) # or sorted(mylist, key=...)

Solution 4 - Python

The answer is to use "sorted", i.e.

sorted(mylist, key=lambda x: x[1])

Solution 5 - Python

Sort and itemgetter is the fastest.

>>> import operator
>>> import timeit

>>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
>>> t1 = timeit.Timer(lambda: mylist.sort(key=lambda x: x[1]))
>>> t1.timeit()
1.6330803055632404

>>> t2 = timeit.Timer(lambda: mylist.sort(key=operator.itemgetter(1)))
>>> t2.timeit()
1.3985503043467773

>>> t3 = timeit.Timer(lambda: sorted(mylist, key=operator.itemgetter(1)))
>>> t3.timeit()
2.6329514733833292

>>> t4 = timeit.Timer(lambda: sorted(mylist, key=lambda x: x[1]))
>>> t4.timeit()
2.9197154810598533

Solution 6 - Python

Solution of your question is: sorted_list = sorted(mylist, key=lambda value:value[1])

Solution for dictionary of list is:

mylist = [{'name':'kk', 'age':21},{'name':'bk', 'age':21}]

sorted_list = sorted(mylist, key=lambda k: k['key_name'])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser248237View Question on Stackoverflow
Solution 1 - PythonScott StaffordView Answer on Stackoverflow
Solution 2 - PythonStephenView Answer on Stackoverflow
Solution 3 - PythonWill McCutchenView Answer on Stackoverflow
Solution 4 - Pythonuser248237View Answer on Stackoverflow
Solution 5 - PythonrizaView Answer on Stackoverflow
Solution 6 - PythonKrishna KumarView Answer on Stackoverflow