python3 自定義比較器

2021-09-28 22:27:47 字數 1207 閱讀 9755

摘要:在一些場景中,需要重新對已有的資料排序,可能所給出的資料型別或者資料數量較多,需要給定排序規則。

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]:

return 0

else:

return -1

def md():

datas=[['bob', 99,1],['bart', 66,2],['bob', 29,3], ['adam', 92,4],['bob', 29,5], ['adam', 90,6], ['bart', 66,7], ['lisa', 88,8]]

datas.sort(key=functools.cmp_to_key(by_score)) # 穩定排序

print(datas)

#[['adam', 90, 6], ['adam', 92, 4], ['bart', 66, 2], ['bart', 66, 7], ['bob', 29, 3], ['bob', 29, 5], ['bob', 99, 1], ['lisa', 88, 8]]

class pos:

def __init__(self,x,y):

self.x=x

self.y=y

def cmp(a, b):

return a.x - b.x if a.x != b.x else a.y - b.y # x y均按照從小到大的順序

def mysorted():

test_list = [pos(5, 1), pos(2, 5), pos(2, 4)]

# test_list.sort(key=functools.cmp_to_key(lambda a,b: a.x-b.x if a.x != b.x else a.y-b.y))

test_list.sort(key=functools.cmp_to_key(cmp))

# sorted(test_list, key=functools.cmp_to_key(cmp)) # 親測此方法不能成功排序

for number in test_list:

print(number.x,' ',number.y)

python3 自定義比較函式

python 2 中支援類似 c 中 cmp 的寫法 python 3 放棄了這一用法 官方說明 所以不想寫lambda的話,加一句cmp to key 就行了 def 比較函式 return 原來的方式是 sorted cmp 比較函式 現在的方式是 from functools import c...

python3自定義函式

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

Python3 自定義比較排序 運算子

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