sorting lists in python 3

gyrfalcon picture gyrfalcon · Jun 1, 2013 · Viewed 12.2k times · Source

So, I need to sort this kind of list with some random data in it by first element of second nested list (with elements like 01, 02, 03, etc):

  [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]

this random data is later used in defaultdict with some other data, in order to group it together and print it out by key (the keys are numbers like 00553, 00551).

I tried to sort it before putting it to defaultdict but all I am getting sorted out is values of nested list itself..

can anybody please help me, I am new in this.

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Jun 1, 2013
>>> lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
>>> sorted(lis, key = lambda x: int(x[1][0])) 
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]