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

匿名函数

- 传入列表
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(lambda x: x * x),[1, 2, 3, 4, 5, 6, 7, 8, 9])

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

map reduce filter

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