Gopi
Gopi

Reputation: 21

Sorting lists based on a particular element - Python

How do I sort a list of lists based on the first element of the lists in Python?

>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
>>> map(sorted, list01)
[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']]
>>> sorted(map(sorted, list01))
[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']]

Upvotes: 2

Views: 1951

Answers (4)

Debanshu Kundu
Debanshu Kundu

Reputation: 805

Apart from the passing a key function to the sorted (as show in earlier answers) you can also pass it a cmp (comparison) function in Python2 as follows:

sorted(list01, cmp=lambda b, a: cmp(b[0], a[0]))

Output of above expression would be same as that of using the the key function.

Although they have removed the cmp argument in Python3 from sorted, https://docs.python.org/3.3/library/functions.html#sorted, and using a key function is the only choice.

Upvotes: 0

Johannes Charra
Johannes Charra

Reputation: 29913

from operator import itemgetter    
sorted(list01, key=itemgetter(0))

Upvotes: 1

OzTamir
OzTamir

Reputation: 131

Python's sorted() can receive a function to sort by. If you want to sort by the first element in each sublist, you can use the following:

>>> lst = [[2, 3], [1, 2]]
>>> sorted(lst, key=lambda x: x[0])
[[1, 2], [2, 3]]

For more information on sorted(), please see the official docs.

Upvotes: 1

ljetibo
ljetibo

Reputation: 3094

>>> sorted(list01, key=lambda l: l[0])
[['a', 'b', 'c'], ['a', 'f', 'd'], ['b', 'a', 'd'], ['d', 'e', 'c']]

Is this what you mean?

Upvotes: 0

Related Questions