2014年3月16日 星期日

[Python] key function for sorting

Example
 def checkio(numbers_array):  
   list_num = list(numbers_array)  
   list_num = sorted(list_num, key=abs)  
   return list_num  


[Note]

1. The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes

2. A common pattern is to sort complex objects using some of the object's indices as a key
Example 
>>> student_tuples = [  
     ('john', 'A', 15),  
     ('jane', 'B', 12),  
     ('dave', 'B', 10),  
 ]  
 >>> sorted(student_tuples, key=lambda student: student[2])  # sort by age  
 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]  

[Ref]

https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions

沒有留言:

張貼留言