python - 将功能传递给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)
它显示错误。
解决方案
也许这会有所帮助:
给定这个函数定义/返回值:
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))
认为它应该以与排序功能相同的方式工作。
推荐阅读
- linux - 我可以通过书签启动 vim
- typescript - 动态导入不适用于导出的模块打字稿
- javascript - 电子中的定时功能
- c - 计算数组中有多少个数满足特定条件的函数
- django - django-rest-framework get_schema_view:TypeError:“文档”类型的对象不是 JSON 可序列化的
- angular - 将 asp.net 核心 API 与主机中的 Angular 应用程序集成
- airflow - Apache Airflow AttributeError:“NoneType”对象没有属性“create_dagrun”
- javascript - 新日期没有给我正确的价值
- swiftui - 我无法让我的 LazyVGrid 显示超过两行
- python - User.query.filter_by(id=user_id).first() 和 User.query.get(user_id) 在 Flask Sql Alchemy 中返回 None