简体   繁体   中英

How to efficiently define custom global comparator in Python 3?

I want to define comparator like:

def cmp_smth(x, y):
    if x == y:
        return 0
    elif fn(x, y):
        return -1
    else:
        return 1
comparator = functools.cmp_to_key(cmp_smth)

And it works fine with cmp_to_key converter, ie:

sorted([x, y, z], key=comparator)

But what if I want to sort something more complicated, ie tuples:

sorted([(1, x), (2, y), (3, z)], key=???)

How to use my global comparator in this case?

您可以使用lambda将键函数(以前是比较器)映射到每个元组的第二个元素:

sorted([(1, x), (2, y), (3, z)], key=lambda x: comparator(x[1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM