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')
输出:
False 外1 8
True 内 3
True 外1 1
True 内 2
True 内 5
True 外1 4
True 内 7
True 外1 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
写入自己的博客中才能记得长久