1

python3 sort cmp问题

 1 year ago
source link: https://cfonheart.github.io/2018/09/17/python3-sort-cmp%E9%97%AE%E9%A2%98/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python3 sort cmp问题

2018-09-17

根据自定义的数据结构进行排序, 希望按照能够像c/c++中的写法一样自定义cmp函数。

python2中是支持的,但是python3取消了cmp的关键字,可以通过functools.cmp_to_key达到同样的效果

demo样例如下:

from functools import cmp_to_key
import sys
class A:
def __init__(self, x, y):
self.x = x
self.y = y
def cmp_a(a, b):
if a.x < b.x or (a.x == b.x and a.y < b.y):
return -1
elif a.x == b.x and a.y == b.y:
return 0
else:
return 1
a_list = []
a_list.append(A(4, 5))
a_list.append(A(3, 5))
a_list.append(A(4, 3))
a_list.append(A(3, 4))
a_list.append(A(4, 4))
if sys.version_info[0] == 3:
a_list.sort(key=cmp_to_key(cmp_a))
# sorted(a_list, key=cmp_to_key(cmp_a)) # 上下两行功能一致
else:
a_list.sort(cmp=cmp_a)
for a in a_list:
print (a.x, a.y)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK