在python2中,cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
而在python3中没有cmp函数,转而使用的是 operator 函数。
函数 | 含义 |
---|---|
operator.eq(x, y) | x == y |
operator.ne(x,y) | x != y |
operator.lt(x, y) | x < y |
operator.le(x,y) | x <= y |
operator.gt(x,y) | x > y |
operator.ge(x,y) | x >= y |
栗子1:
import operator
print(operator.lt(1, 2))
结果为: True
Key 排序
栗子1:
print(sorted([1, -2, 0, 5], key=abs))
print(sorted([1, -2, 0, 5], key=lambda x: abs(x)))
结果为: [0, 1, -2, 5] [0, 1, -2, 5]
栗子2:
list1 = [('david', 90), ('mary', 90), ('sara', 80), ('lily', 95)]
L1 = sorted(list1, key=lambda x: x[0])
L2 = sorted(list1, key=lambda x: x[1])
print(L1)
print(L2)
结果为:
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
用operator.itemgetter函数排序
from operator import itemgetter
list1 = [('david', 90), ('mary', 90), ('sara', 80), ('lily', 95)]
L1 = sorted(list1, key=itemgetter(0))
print(L1)
L2 = sorted(list1, key=itemgetter(1))
print(L2)
结果为:
[('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
[('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
operator.itemgetter函数
import operator
a = [1, 2, 3, 4, 5]
b = operator.itemgetter(3)
print(b(a))
结果为: 4
既然cmp不能用,operator不会用,试试这样的:
from functools import cmp_to_key
nums = [1, 3, 9, 5, 0]
print(sorted(nums, key=cmp_to_key(lambda a, b: a - b)))
结果为: [0, 1, 3, 5, 9]
from functools import cmp_to_key
nums = [1, 3, 9, 5, 0]
print(sorted(nums, key=cmp_to_key(lambda a, b: b - a)))
结果为: [9, 5, 3, 1, 0]
大家加油!