3、高阶函数:map/reduce/filter/sorted
2019-02-12 本文已影响0人
小书bluebirds
1、map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回

2、reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

3、filter
filter()函数用于过滤序列。
filter()也接收一个函数和一个序列。filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

4、sorted
sorted()函数就可以对list进行排序

sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序
key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序
要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True

