python笔记十四(高阶函数——map/reduce、filter、sorted)

一、map/reduce

  1.map()

  map(f,iterable),将一个iterable对象一次作用于函数f,并返回一个迭代器。

  

>>> def f(x):   #定义一个函数
...     return x*x
...
>>> L = list(range(10))#生成一个列表,它是 Iterable
>>> map(f,L) #调用map函数
<map object at 0x000001AB00C1AC18>
>>> obj = map(f,L)
>>> next(obj)
0
>>>
>>> next(obj)
1
>>> next(obj)
4
>>> next(obj)
9
>>> for i in obj:
...     print(i)
...
16
25
36
49
64
81

>>> isinstance(obj,Iterator)    #可以看到返回的obj是一个Iterator
True

  2.reduce()

  reduce(f,Iterable),把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:特点是把第一次函数运算的结果作为第二次运算的第一个参数。

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

>>> L = list(range(10))  #创建一个列表
>>> def f(x1,x2):
...     return x1*10+x2
...
>>> reduce(f,L)
123456789

  map和reduce的混合使用实现从str转化为int

>>> from functools import reduce
>>> DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
>>> def char2num(s):
...     return DIGITS[s]
...
>>> def str2int(s):
...     return reduce(lambda x, y: x * 10 + y, map(char2num, s))
...
>>> str2int("654321")
654321

 

二、filter函数

  filter(f,Iterable),和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后如果返回值是True保留该元素,False丢弃该元素。返回的也是一个Iterator.

>>> def f(x):
...     return x%2==0
...
>>> f(0)
True
>>> from collections import Iterator
>>> f = filter(f,[0,1,2,3,4,5])
>>> isinstance(f,Iterator)
True
>>> next(f)
0
>>> next(f)
2
>>> next(f)
4
>>> next(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

三、sorted

  sorted()我们用来排序,除了默认的排序方式,我们还可以自定义排序的规则。

  sorted(l,key=f) 例如key=abs,这里的abs是求绝对值的函数,我们就会按照绝对值的方式排序。

>>> abs(-1)
1
>>> sorted([-9,-3,-1,2,4,6],key=abs)
[-1, 2, -3, 4, 6, -9]

>>> sorted([-9,-3,-1,2,4,6],key=abs,reverse=True)
[-9, 6, 4, -3, 2, -1]

  按照首字母排序,不考虑大小写。

>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

 

posted @ 2017-12-22 16:30  nadech  阅读(214)  评论(0编辑  收藏  举报