python中的内置高阶函数

python中的内置高阶函数,第1张

文章目录
  • map 函数
  • reduce 函数
    • ((((1+2)+3)+4)+5)= reduce result
  • 3.filter 筛选
  • 4.sorted:排序

map 函数
result = map(lambda x: x ** 2, [1, 2, 4, 5])
print(list(result))

result = map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])
print(list(result))

reduce 函数 ((((1+2)+3)+4)+5)= reduce result
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result)

3.filter 筛选
result = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 8])
print(list(result))     # 筛选出所有的偶数
result = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 8])
print(list(result))     # 筛选出所有的奇数

4.sorted:排序
result = sorted([1, 29, 2, 3])
print(result)
result = sorted([1, 29, 2, 3], reverse=True)
print(result)
result = sorted([0, 8, 9, 0, 16] , key=lambda x:0 if  x==0 else 1)
print(result)

eg :实现100的阶乘的运算!

result  = reduce(lambda x, y: x * y, range(1, 101))
print(result) 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/570738.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-09
下一篇2022-04-09

发表评论

登录后才能评论

评论列表(0条)

    保存