pythonsorted_Python高阶函数及sorted函数原理

高阶函数

函数在Python中是一等公民

函数也是对象,可调用的对象

函数可以作为普通变量,参数,返回值等

成为高阶函数的必要条件:

接收一个或多个函数作为参数

输出一个函数

示例:

defcounter(base):def inc(step=1):

nonlocal base

base+= step #base = base + step ,使用局部变量,但是此没有base局部变量,需要使用nonlocal base,申明为不是本地变量向外找,则形成闭包

returnbasereturninc

f= counter(10)print(f())#输出

11f1= inc(5)

f2= inc(5)

f1is f2,f1 == f2,id(f1),id(f2) #函数内容无法比较,会转换成比较内存地址,即转换成f1 is f2

结果都是False‘‘‘f1,f2都是指向内部函数inc,每次调用counter函数执行都需要创建栈针、压栈、将函数值返回弹出栈顶,之后counter函数消亡,但存在闭包f1记录了inc函数的内存地址,每次都是全新的函数调用,

所以f1 f2内存地址不一样,函数之间无法比较内容,会隐式转换成比较内存地址即 f1 == f2 --> f1 is f2‘‘‘

自定义sort()函数:

仿照sorted()内嵌函数,自行实现一个sort函数,能够为列表元素排序

#No 1 升序打印

def sort(iterable,*, key=None, reverse=False):

newlist=[]for x initerable:for i,y inenumerate(newlist):if x

newlist.insert(i,x)break

else:

newlist.append(x)returnnewlistprint(sort([1,9,8,5]))

#[1,5,8,9]

实现reverse=True,逆序打印

def sort(iterable,*, key=None, reverse=False):

newlist=[]for x initerable:for i,y inenumerate(newlist):

compare= x > y if reverse else x

newlist.insert(i,x)break

else:

newlist.append(x)returnnewlistprint(sort([1,9,8,5],reverse=True))

#[9,8,5,1]

实现key=None转换,排序

def sort(iterable,*, key=None, reverse=False):

newlist=[]for x initerable:

cx= key(x) if key elsexfor i,y inenumerate(newlist):

cy= key(y) if key elsey

compare= cx > cy if reverse else cx

newlist.insert(i,x)break

else:

newlist.append(x)returnnewlist#print(sort([1,9,8,5,‘a‘],key=str))

print(sort([1,9,8,5,‘a‘],key=lambda x : str(x)))

内键高阶函数:

排序sorted:sort(iterable,*, key=None, reverse=False)

sorted([1,9,8,5,‘a‘],key=str) #报错,不同类型无法比较

sorted([1,9,8,5,‘a‘],key=str)

sorted([1,9,8,5,‘a‘],key=lambdax : str(x))

sorted([1,9,8,5,‘a‘],key=lambda x : int(x,16) if isinstance(x,str) else x)

sorted([1,9,8,5,‘a‘],key=lambda x : ord(‘a‘) if isinstance(x,str) else x)

过滤filter:filter(self, /, *args, **kwargs)

filter(function or None, iterable)

对可迭代对象进行遍历,返回一个迭代器,

function参数是一个参数的函数,,且返回值应当是bool类型,或其返回值等效于bool

function参数如果是None,则可迭代对象的每一个元素自身等效于bool

filter过滤元素个数当条件满足则一定减少,否则不变,长度小于等于原始数据

list(filter(lambda x : x%3 !=0 ,range(5)))

[1,2,4]

list(filter(lambda x : x%3 ==0 ,range(5)))

[0,3]

list(filter(None,range(5))) #如果filter第一个参数为None,则按照元素本身等效TRUE of false ,false 则过滤掉

[1,2,3,4]

list(filter(None,range(-1,2))) #如果filter第一个参数为None,则按照元素本身等效TRUE of false ,false 则过滤掉

[-1,1,2]

list(filter(lambda x : None,range(5))) #不管写什么都给返回None,则全部过滤

[]

映射map(变形)

定义map(func, *iterables) --> map object

对多个可迭代对象的元素,按照指定的函数进行映射

返回一个迭代器,惰性对象

list(map(lambda x : 2 ,range(5))) #按照指定的函数进行映射,则x不管给什么值都是返回2

[2, 2, 2, 2, 2]

list(map(lambda x : 6-x ,range(5)))

[6, 5, 4, 3, 2]

list(map(lambda x,y: (x,y),‘abced‘ ,range(5)))

[(‘a‘, 0), (‘b‘, 1), (‘c‘, 2), (‘e‘, 3), (‘d‘, 4)]

dict(map(lambda x : x, zip(‘abced‘ ,range(5)))) #等效 dict(zip(‘abced‘ ,range(5)))

{‘a‘: 0, ‘b‘: 1, ‘c‘: 2, ‘e‘: 3, ‘d‘: 4}#但是使用map能对原有元素进行变形比较方便,如下所示:

dict(map(lambda x : (x[0],str(x[1])), zip(‘abced‘ ,range(5))))

原文地址:https://www.cnblogs.com/alrenn/p/12728433.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值