Python Sort a list by multiple attributes with one line of code
Suppose we have a list of record
1
2
3
4
5
6
7
records =
(
 (department, name, salary),
 (department, name, salary),
 ...
 (department, name, salary)
)
Then we want to sort the records first by 'department', and then by 'salary'
Maybe it would a little complex in other programming language. But in python, it would be as simple as one line as follows: 
1
2
3
records.sort(
 key = lambda l: (l[0], l[2])
)
I think this is the amazing part of functional programming that you can create an anonymous inline function to do this.  
Suppose we have another dictionary  { name: ages } linked with the records list,  we can also do sorting according to some external as follows : 
1
2
3
record.sort(
 key = lambda l:( l[0], dictionary_age(l[1]) )
)
If you want to rank the records in descending order, just set reverse = True; if you want to rank in a way that one attribute in descending order and one in ascending order, you have to a cmp function. 
Done!

0 comments

Popular Posts

无觅相关文章插件,迅速提升网站流量