在python中将函数传递到排序 定义函数(l1,l2): 如果(abs(l1[0]-l1[1])>abs(l2[0]-l2[1]): 返回真值 如果(abs(l1[0]-l1[1])==abs(l2[0]-l2[1]): 如果(l1[0]
我想在在python中将函数传递到排序 定义函数(l1,l2): 如果(abs(l1[0]-l1[1])>abs(l2[0]-l2[1]): 返回真值 如果(abs(l1[0]-l1[1])==abs(l2[0]-l2[1]): 如果(l1[0],python,sorting,Python,Sorting,我想在sorted()函数如何操作中将此函数作为关键参数传递。当我这样路过的时候 排序(lis,key=a_func)显示错误。这可能会有帮助: 给定此函数定义/返回值: 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]
sorted()
函数如何操作中将此函数作为关键参数传递。当我这样路过的时候
排序(lis,key=a_func)
显示错误。这可能会有帮助:
给定此函数定义/返回值:
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
其中,hand_1、hand_2、mapped_hand_1、mapped_hands_2是5个有序对的元组
对于使用cmp_to_键调用此函数的代码,functools:
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
可能就是你要找的
我将其与max函数一起使用:
from functools import cmp_to_key
# Stuff....
winners.sort(key=cmp_to_key(hand_1_higher_than_hand_2))
我认为它应该与排序函数的工作方式相同。请同时给出数组输入示例和导出输出(通过编辑您的帖子)。sorter方法只接受1个参数并为其返回一个值,然后每个对象的每个“值”都将被比较,这不像java那样将对象2乘以2进行比较。sort
键
函数接受一个参数,并将其转换为可以排序的值。不需要两个参数来相互比较。排序回调也不应该返回没有意义的True
或False
。引用文档:“key指定一个参数的函数,用于从iterable中的每个元素提取比较键(例如key=str.lower)。默认值为None(直接比较元素)。”。这与该签名不匹配。您可能需要类似于def a_func(l):返回abs(l[0]-l[1])、l[0]
,它根据第一个索引和第二个索引之间的绝对差以及第一个索引本身的相等性进行排序。
winning_hand = max(winners, key=cmp_to_key(hand_1_higher_than_hand_2))