【发布时间】:2018-01-18 04:45:34
【问题描述】:
我有一个类似于this 问题的自定义排序功能。但是,我有一个列表值 - 如果存在 - 必须排序到列表的末尾(到最后一个位置)。这可以在自定义排序函数中实现吗?
我考虑过以下几点:
mylist.sort(cust_sort)
def cust_sort(item1, item2):
if item1.key == critical_value:
#If the item1 in question is the "must be last" item, place it last.
return -99
#There should never be more than 99 items in this list, but
# this number could be as large as necessary.
if item1.key > item2.key:
return 1
elif item1.key < item2.key:
return -1
if item1.name > item2.name:
return 0
return 0
注意:我想尽可能地限制我实施此修复的范围 - 如果可能的话,仅限于此自定义排序功能。我知道我可以删除这个临界值,执行排序,然后重新添加临界值。然而,这是遗留代码并且已经相当混乱 - 直接在自定义排序函数中实现修复将操作范围之外的影响降至最低。我更愿意最大限度地提高可读性并尽量减少干扰。
【问题讨论】:
-
您正在处理什么样的对象?如果您可以映射到数字,那么您可以利用
float('inf')或float('-inf') -
item.key 是 int 或 int 作为字符串。
-
还有.. 你在 Python 2 上吗?
-
是的,python 2.7
标签: python sorting customization short-circuiting