python3 自定義比較函式

2021-08-16 20:05:03 字數 726 閱讀 2983

python 2 中支援類似 c++ 中 cmp 的寫法

python 3 放棄了這一用法

官方說明:

所以不想寫lambda的話,加一句cmp_to_key()就行了

def 比較函式():

...return ...

原來的方式是:

.sorted(cmp=比較函式)

現在的方式是:

from functools import cmp_to_key

.sorted(key=cmp_to_key(比較函式))

舉例:

對字串排序,要求把開頭為'x'的排到前面,然後再以字典序排。

from functools import cmp_to_key

def cmpp(s1,s2):

if s1[0] == 'x' and s2[0] != 'x':

return 1

if s2[0] == 'x' and s1[0] != 'x':

return -1

if s1 > s2:

return -1

if s1 < s2:

return 1

return 0

def front_x(words):

t = sorted(words,key=cmp_to_key(cmpp),reverse=1)

return t

python3 自定義比較器

摘要 在一些場景中,需要重新對已有的資料排序,可能所給出的資料型別或者資料數量較多,需要給定排序規則。import functools def by score t1,t2 if t1 0 t2 0 return 1 elif t1 0 t2 1 return 1 elif t1 1 t2 1 re...

python3自定義函式

一 什麼是函式 函式是組織好的,可重複使用的,用來實現單一,或相關聯功能的 段。函式能提高應用的模組性,和 的重複利用率。你已經知道python提供了許多內建函式,比如print 但你也可以自己建立函式,這被叫做使用者自定義函式。語法def 函式名 引數列表 函式體def func print 王小...

Python3 自定義比較排序 運算子

python3和python2相比有挺多變化。在python2中可以直接寫乙個cmp函式作為引數傳入sort來自定義排序,但是python3取消了。在這裡總結一下python3的自定義排序的兩種寫法,歡迎補充。我們以二維空間中的點來作為待排序的資料結構,我們希望能先比較x後再比較y。class po...