python之自定義排序函式sorted()
阿新 • • 發佈:2019-01-11
sorted()也是一個高階函式,它可以接收一個比較函式來實現自定義排序,比較函式的定義是,傳入兩個待比較的元素 x, y,如果 x 應該排在 y 的前面,返回 -1,如果 x 應該排在 y 的後面,返回 1。如果 x 和 y 相等,返回 0。
def custom_sort(x,y): if x>y: return -1 if x<y: return 1 return 0 print sorted([2,4,5,7,3],custom_sort)
在python3以後,sort方法和sorted函式中的cmp引數被取消,此時如果還需要使用自定義的比較函式,那麼可以使用cmp_to_key
def custom_sorted(x,y): if x>y: return -1 if x<y: return 1 return 0 print(sorted([2,3,1,5,4],key=cmp_to_key(custom_sorted)))