应用场景:渲染用户界面时,因为关键的消息和特殊的事件应该优先显示在其他信息之前。
numbers = [8, 3, 1, 2, 5, 4, 7, 6] //原始数据
group = {8, 3, 5, 7} //优先级高的数据,
def sort_priority(numbers, group):
found = False
def helper(x):
nonlocal found
if x in group:
found = True
return 0, x
return 1, x
numbers.sort(key=helper)
return found
res = sort_priority(numbers, group)
print(res, numbers) //打印
完善用类方法实现
# 优化 类方法
class Sorter:
def __init__(self, group):
self.group = group
self.found = False
def __call__(self, x):
if x in self.group:
self.found = True
return 0, x
return 1, x
sorter = Sorter(group)
numbers.sort(key=sorter)
print(numbers)
assert sorter.found is True
输出结果
True [3, 5, 7, 8, 1, 2, 4, 6]
[3, 5, 7, 8, 1, 2, 4, 6]
标签:__,多重,group,self,元素,return,numbers,found,排序 From: https://www.cnblogs.com/DTCLOUD/p/17291724.html作者:朱海波