Monday, July 23, 2012

Python: multiple sorted with keys

Today I encounter a problem of sorting an array or a list twice, first by index key1, then by index key2.

More specificlly:

ththings  = [("animal", "bear"), ("vehicle", "school bus"),("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat")]

And I want it first be arranged by the first index alphabetically, and then within each class, i.e. 'animal', 'vehicle', 'plant', the second index also should be arranged alphabetically like:
[('animal', 'bear'),
 ('animal', 'duck'),
 ('plant', 'cactus'),
 ('vehicle', 'school bus'),
 ('vehicle', 'speed boat')]

The solution to this problem is to use sorted() function twice, but the tricky thing is that, we must sorted the by the second index inside the sorting of the first index:

c = sorted((sorted(things, key=lambda x: x[1])), key=lambda x:x[0])

where x[1] refers to the 2nd column of the array 'things'.

No comments:

Post a Comment