+2 votes
in Programming Languages by (73.8k points)

I want to sort a list of lists by some specific index of the inner list. How can I do?

E.g.:

a=[[12,'2003-10-12'],[15,'2002-01-12'],[23,'2001-03-12'],[10,'2001-02-23'],[43,'2001-02-10']]

I want to sort the above list by second value date in the sublists.

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

I am aware of two ways to sort a list of list by some index of the inner list. Check the following examples:

Using lambda function

>>> a=[[12,'2003-10-12'],[15,'2002-01-12'],[23,'2001-03-12'],[10,'2001-02-23'],[43,'2001-02-10']]

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

[[43, '2001-02-10'], [10, '2001-02-23'], [23, '2001-03-12'], [15, '2002-01-12'], [12, '2003-10-12']]

Using itemgetter() of operator module

>>> from operator import itemgetter

>>> sorted(a, key=itemgetter(0))

[[10, '2001-02-23'], [12, '2003-10-12'], [15, '2002-01-12'], [23, '2001-03-12'], [43, '2001-02-10']]

>>> sorted(a, key=itemgetter(1))

[[43, '2001-02-10'], [10, '2001-02-23'], [23, '2001-03-12'], [15, '2002-01-12'], [12, '2003-10-12']]

>>> sorted(a, key=itemgetter(0,1))

[[10, '2001-02-23'], [12, '2003-10-12'], [15, '2002-01-12'], [23, '2001-03-12'], [43, '2001-02-10']]

Reference: https://wiki.python.org/moin/HowTo/Sorting/ 


...