首页 > 编程语言 > 详细

sort()方法 | sorted()函数 | __call__()方法 | Python

时间:2018-01-09 20:58:51      阅读:324      评论:0      收藏:0      [点我收藏+]
#     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

 

sort()方法 | sorted()函数 | __call__()方法 | Python

原文:https://www.cnblogs.com/pymkl/p/8253528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!