cmp(list1, list2) -> int
返回 -1(list1 < list2)、0(相等)、1(list1 > list2)。僅存在於 Python 2,Python 3 移除。
1 < 2.0)。'list' < 'tuple')。
list1, list2 = [123, 'xyz'], [456, 'abc']
print(cmp(list1, list2)) # -1 (123 < 456)
print(cmp(list2, list1)) # 1
list3 = list2 + [786]
print(cmp(list2, list3)) # -1 (list2 為 list3 前綴,較短故小)
from functools import cmp_to_key
def my_cmp(a, b):
return (a > b) - (a < b) # 返回 -1/0/1
sorted_list = sorted(data, key=cmp_to_key(my_cmp))
# Python 3 列表直接支援 < > == 比較,語義同 cmp
[1,2] < [1,3] # True
[1,2] < [1,2,3] # True
若需三態返回值(-1/0/1),可封裝:
def cmp(a, b):
return (a > b) - (a < b)
operator 模組
from operator import eq, lt, gt
# 組合使用
cmp() 是 Python 2 歷史遺留,核心邏輯為「字典序 + 類型名稱兜底」。Python 3 採用原生豐富比較協議(__lt__、__eq__ 等),配合 functools.cmp_to_key 即可無縫遷移舊式比較函數。