Python: Sort list of tuples by second item
Straight from the PythonInfo Wiki:
>>> import operator
>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Related:
- JIRA issues reporting with Python I recently took interest in knowing how one of the...
- Django template filter: Show list of objects as table with fixed number of columns I recently ran into the following problem: I needed to...
Categorised as: code snipplets, software development, tips