码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-09 21:15:11      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:self   __call__   接口   可迭代对象   定义   blog   ted   作用   close   

#     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

标签:self   __call__   接口   可迭代对象   定义   blog   ted   作用   close   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!