匿名函数
- 当我们在传入函数时,有些时候不需要显式地定义函数,直接传入匿名函数更方便
- 关键字 lambda 表示匿名函数,冒号前面的 x 表示函数参数
- 匿名函数有只能有一个表达式,不用写 return ,返回值就是该表达式的结果
- 匿名函数也是一个函数对象,可以把匿名函数赋值给一个变量,再利用变量来调用该函数;
- 可以把匿名函数作为返回值返回
匿名函数定义规则: lambda 形参:返回值
eg:
import random
li=[random.randint(1,10) for i in range(10)]
print(li)
print(sorted(li,key=lambda x:x%2==0))
print(sorted(li,key=lambda x:1 if x%2==0 else 0))
高阶函数
把函数当成参数传递的一种函数
- 实参是一个函数名
- 或者函数的返回值是一个函数
1)函数本身也可以赋值给变量,即:变量可以指向函数
print(abs(-10))
f=abs
print(f(-10))
2)传递的参数包含函数名
def fun(x,y,f):
return f(x),f(y)
print(fun(10,-34,abs))
内置高阶函数
- map()函数
map() 函数接收两个参数,一个是函数,一个是序列, map 将传入的函数依次作用到序列的每个元素,并把结果作为新的 list 返回。
eg:
import random
#对序列每个元素求阶乘
def factoria(x):
"""对于x求阶乘"""
res=1
for i in range(1,x+1):
res=res*i
return res
li=[random.randint(2,7) for i in range(10)] #生成10个2~7的数
print(list(map(factoria,li))) #依次进行求阶乘
- reduce函数
reduce 把一个函数作用在一个序列[x1, x2, x3…]上,这个函数必须接收两个参数,reduce 把结果继续和序列的下一个元素做累积计算。
eg1:
#python2中为内置函数,python3中需要导入
from functools import reduce
def multi(x,y):
return x*y
print(reduce(multi,range(1,5)))
eg2:
import random
from functools import reduce
li=[random.randint(2,6) for i in range(5)] #随机生成5个2~6的数
def multi(x,y):
return x*y
print(reduce(multi,li))
- filter()函数
filter() 也接收一个函数和一个序列。和 map() 不同的时,filter() 把传入的函数依次作用于每个元素,然后根据返回值是 True还是 False 决定保留还是丢弃该元素。
eg1:寻找偶数
def isodd(x):
return x%2==0
# if x%2==0:
# return True
# else:
# return False
print(list(filter(isodd,range(1,11))))
eg2:找素数
def isprime(num):
for i in range(2,num):
if num%i==0:
return False
else:
return True
print(list(filter(isprime,range(2,30))))
- max-min函数
eg1:
l=['hello','a','dhcp','https']
print(max(l,key=lambda x:len(x)))
print(min(l,key=lambda x:len(x)))
eg2:
d={
'user2':{1,4,6,7},
'user3':{3,4,5,8},
'user4':{2,5,6},
'user5':{4,6,8,9}
}
#user1喜欢的电影
film={3,6,7}
#找出字典中跟user1最相似的(即和user1的交集)
maxfilms=max(d.values(),key=lambda x:x & film)
print(maxfilms)
print('推荐给user1的电影:',maxfilms-film)
sort和sorted函数
-
区别
1). 列表里面提供了sort方法, 其他数据结构没有.sorted方法可以对任何可迭代对象排序.
2).sort方法支持原地排序(变量排序后,变量本身改变), sorted排序后返回一个新的列表,并不改变原变量的内容. -
默认sort和sorted方法由小到大进行排序, reverse=True时, 由大到小进行排序.
li=[1,6,7,3,4,56,98,4,100]
li.sort() #li.sort(reverse=True)
print(li)
print(sorted(li,reverse=True))
- 对于列表里面嵌套列表进行排序
info=[
#商品名称,商品数量,商品价格
('apple3',200,9),
('banana',100,3),
('apple1',200,4),
('apple4',300,3)
]
#函数定义方法
print('按默认方法排序')
print(sorted(info))
print('按数量进行排序 索引[1]')
def sorted_by_count(x):
return x[1]
print(sorted(info,key=sorted_by_count)) #key代表排序的关键字
print('按价格进行排序 索引[2]')
def sorted_by_price(x):
return x[2]
print(sorted(info,key=sorted_by_price))
#先按照商品数量由小到大排序,如果数量一致,按价格排序
print('按数量价格')
def sorted_by_count_price(x):
return x[1],x[2]
print(sorted(info,key=sorted_by_count_price))
info=[
#商品名称,商品数量,商品价格
('apple3',200,9),
('banana',100,3),
('apple1',200,4),
('apple4',300,3)
]
#匿名函数方法
print('按默认方法排序')
print(sorted(info))
print('按数量排序 索引[1]')
print(sorted(info,key=lambda x:x[1]))
print('按价格排序 索引[2]')
print(sorted(info,key=lambda x:x[2]))
print('按数量价格排序 索引[1] [2]')
print(sorted(info,key=lambda x:(x[1],x[2])))
from operator import itemgetter
print('按默认方法排序')
print(sorted(info))
print('按数量排序 索引[1]')
print(sorted(info,key=itemgetter(1)))
print('按价格排序 索引[2]')
print(sorted(info,key=itemgetter(2)))
print('按数量价格排序')
print(sorted(info,key=itemgetter(1,-2)))
- 对于字典里面嵌套字典进行排序
d={
'003':{
'name':'apple1',
'count':100,
'price':10
},
'002':{
'name':'apple2',
'count':300,
'price':23
},
}
print(d.items())
print(sorted(d.items(),key=lambda x:x[1]['count']))
print(sorted(d.values(),key=lambda x:x['count']))
from operator import itemgetter
d={
'003':{
'name':'apple1',
'count':100,
'price':10
},
'002':{
'name':'apple2',
'count':300,
'price':23
},
}
print(sorted(d.values(),key=itemgetter('price')))
print(sorted(d.values(),key=itemgetter('count','price')))
高阶函数的建立
高阶函数,返回值是一个函数(定义函数并不会执行函数内容, 调用时才会执行.)
def compare1(x):
def compare2(y):
return x>y
return compare2
compare_first=compare1(10)
print(compare_first) #函数名
res=compare_first(3)
print(res)