Pedro Assunção

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:

  1. JIRA issues reporting with Python I recently took interest in knowing how one of the...
  2. 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


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>