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

[py][lc]python高阶函数(匿名/map/reduce/sorted)

时间:2018-02-08 13:44:36      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:http   class   from   com   lis   one   www.   用法   官方   

匿名函数

f = lambda x: x * x
f(2) # x =2
#4


- 传入列表
f = lambda x: x[2]
print(f([1, 2, 3])) # x = [1,2,3]

map使用

传入函数体

def f(x):
    return x*x

r = map(f, [1, 2, 3, 4]) #函数作用在可迭代对象的每一项
#[1, 4, 9, 16]


- 另一个例子
list(map([1, 2, 3, 4, 5, 6, 7, 8, 9], lambda x: x * x))

reduce用法

from functools import reduce
def add(x, y):
    return x*10 + y

print(reduce(add, [1, 2, 3, 4])) #函数作用在可迭代对象的每一项聚合
# 1234

sorted探究

参考:
高阶函数map/reduce

sorted,官方文档写的挺好,可以学到不少东西

sorted(iterable, key=None, rev

[py][lc]python高阶函数(匿名/map/reduce/sorted)

标签:http   class   from   com   lis   one   www.   用法   官方   

原文地址:https://www.cnblogs.com/iiiiiher/p/8430914.html

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