首页 > 解决方案 > 将功能传递给python中的排序

问题描述

def a_func(l1,l2):
    if(abs(l1[0]-l1[1]) > abs(l2[0] - l2[1])):
        return True
    if(abs(l1[0]-l1[1]) == abs(l2[0] - l2[1])):
        if(l1[0] < l2[0]):
            return True
        else:
            return False
    return False

我想将此函数作为函数中的关键参数传递sorted()如何执行。当我这样通过时, sort(lis,key = a_func)它显示错误。

标签: pythonsorting

解决方案


也许这会有所帮助:

给定这个函数定义/返回值:

def hand_1_higher_than_hand_2(hand_1, hand_2):
   # Buncha code that changes hand_1/hand_2 to mapped_hand_1/mapped_hand2

   return mapped_hand_1 > mapped_hand_2

其中 hand_1、hand_2、mapped_hand_1、mapped_hands_2 是 5 个有序对的元组

使用 functools 中的 cmp_to_key 调用它的代码:

from functools import cmp_to_key
# Stuff....
winners.sort(key=cmp_to_key(hand_1_higher_than_hand_2))

可能是你要找的。

我将它与 max 函数一起使用:

    winning_hand = max(winners, key=cmp_to_key(hand_1_higher_than_hand_2))

认为它应该以与排序功能相同的方式工作。


推荐阅读