15.了解如何在闭包里使用外围作用域中的变量, 闭包排序key优先级用法

假如有一份列表,其中的元素都是数字,现在要对其排序,但排序时,要把出现在
某个群组内的数字,放在群组外的那些数字之前。这种用法在绘制用户界面时候可能会
遇到,我们可以用这个办法把重要的消息或意外的事件优先显示在其他内容前面。
实现该功能的一种常见做法,是在调用列表的sort方法时,把辅助函数传给key参
数。这个辅助函数的返回值,将会用来确定列表中各元素的顺序。辅助函数可以判断受
测元素是否处在重要群组中,并据此返回相应的排序关键字(sort key)。

1. 方案一

def sort_priority(values,group):
    def helper(x):
        if x in group:
            return (0,x)
        return (1,x)
    values.sort(key=helper)

numbers = [8,3,1,2,5,4,7,6]
group = {2,3,5,7}
sort_priority(numbers,group)
print(numbers)
输出: [2, 3, 5, 7, 1, 4, 6, 8]

2. 方案二

def sort_priority2(numbers,group):
    found = False
    def helper(x):
        if x in group:
            found = True#Seems simple
            return (0,x)
        return (1,x)
    numbers.sort(key = helper)
    return found


numbers = [8,3,1,2,5,4,7,6]
group = {2,3,5,7}
found = sort_priority2(numbers,group)
print("Found",found)
print(numbers)
输出: 
Found False
[2, 3, 5, 7, 1, 4, 6, 8]

3. 方案三

found='asdf'
def sort_priority(numbers,group):
    found = False
    def helper(x):
        nonlocal found
        if x in group:
            found = True
            print(found,'内',x)
            return (0,x)
        print(found, '外1',x)
        return (1,x)
    numbers.sort(key=helper)
    return found

numbers = [8,3,1,2,5,4,7,6]
group = {2,3,5,7}
sort_priority(numbers,group)
print(numbers)
print(found,'外2')
输出:
False1 8
True3
True1 1
True2
True5
True1 4
True7
True1 6
[2, 3, 5, 7, 1, 4, 6, 8]
asdf 外2

4. 方案四

class Sorter(object):
    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)

numbers = [8,3,1,2,5,4,7,6]
group = {2,3,5,7}
sorter = Sorter(group)
numbers.sort(key=sorter)

print(numbers)
print(sorter.found)
输出:
[2, 3, 5, 7, 1, 4, 6, 8]
True

5. 方案五,Python2中不支持nonlocal,用列表的方式

#Python 2
def sort_priority(numbers,group):
    found = [False]
    def helper(x):
        if x in group:
            found[0] =True
            return (0,x)
        return (1,x)
    numbers.sort(key=helper)
    return found[0]


numbers = [8,3,1,2,5,4,7,6]
group = {2,3,5,7}
found = sort_priority(numbers,group)

print(numbers)
print(found)


输出:
[2, 3, 5, 7, 1, 4, 6, 8]
True
posted @   ty1539  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示