# sort()方法与sorted()函数的区别: # sort()方法是在原可迭代对象直接修改; # sorted()函数是返回一个新的可迭代对象; # 例子:根据列表中哪个数据更靠近10来排序; # 1.lambda() >> list_first = [1,4,7,9,33,22,55,77] >> list_first.sort(key=lambda x:abs(x-10)) >> print(list_first) >> [9, 7, 4, 1, 22, 33, 55, 77] >> list_second = [1,4,7,9,33,22,55,77] >> sorted(list_second, key=lambda x:abs(x-10)) >> [9, 7, 4, 1, 22, 33, 55, 77] # 2.自定义函数 >> def which_closed(x): >> return abs(x-10) >> list_first = [1,4,7,9,33,22,55,77] >> list_first.sort(key=which_closed) >> print(list_first) >> [9, 7, 4, 1, 22, 33, 55, 77] # 3.类模拟函数 | __call__() >> class WhichClosed(object): >> def __init__(self,select_num): >> self.select_num = select_num >> def __call__(self,x): >> return abs(x-self.select_num) >> list_first = [1,4,7,9,33,22,55,77] >> list_first.sort(key=WhichClosed(10)) >> print(list_first) >> [9, 7, 4, 1, 22, 33, 55, 77] # __call__()作用:使对象变成可调用接口 >> class WhichClosed(object): >> def __init__(self,select_num): >> self.select_num = select_num >> def __call__(self,x): >> return abs(x-self.select_num) >> obj = WhichClosed(10) # 实例化对象 >> obj(2) # 对象加上小括号时,对象内部调用__call__()方法; >> 8
原文地址:https://www.cnblogs.com/pymkl/p/8253528.html
时间: 2024-10-26 19:52:25