python中常见的内置高阶函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37653394/article/details/82955415

常见的内置高阶函数:map,reduce,filter,sorted

在python3中,reduce已经不算是内置函数了,据说是因为龟叔不喜欢map / reduce这样的内置函数,但是在社区的极力反对下,保留了下来,不过放在了functools包中。

from functools import reduce

-- map(func, iterable)


map函数接收两个参数,第一个参数为一个函数,第二个参数为一个iterable对象,返回一个iterator对象

func只能有一个位置参数,它是作用在iterable对象的每一个元素上。

In [43]: name = ['adam', 'LISA', 'barT']

In [44]: def normalize(name):
    ...:     return name.capitalize()
    ...:
    ...:

In [45]: list(map(normalize, name))
Out[45]: ['Adam', 'Lisa', 'Bart']

-- reduce(func, sequence[, initial])


reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

func函数似乎只能接收两个位置参数,超过两个似乎就不行了。reduce的作用就是,从左到右,使用func函数对sequence中的没两个参数进行计算,得到一个结果然后又和右边的值作为参数传入到func中进行计算,知道sequence全部计算完毕,最后返回一个总的结果。其效果相当于这样:

reduce(func, [a,b,c,d])
<==>
func(func(func(a,b),c),d)

举个栗子,求累积:

In [56]: def multi(x,y):
    ...:     return x*y
    ...:
    ...:

In [57]: reduce(multi, range(1,11))
Out[57]: 3628800

求三个数的和,出bug啦:

In [50]: def add(x,y,z):
    ...:     return x+y+z
    ...:
    ...:

In [51]: reduce(add, range(1,10))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-46346e8f5e3e> in <module>()
----> 1 reduce(add, range(1,10))

TypeError: add() missing 1 required positional argument: 'z'

再举个栗子://将数字字符串转换为整数

In [54]: def str2int(s):
    ...:     DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    ...:     return reduce(lambda x,y:x*10+y, map(lambda x:DIGITS[x], s))
    ...:
    ...:

In [55]: str2int("2321423432")
Out[55]: 2321423432

-- filter(func or None, iterable)


filter(function or None, iterable) --> filter object
 |
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.

filter函数接收两个参数,返回一个迭代器。func作用于序列的每个元素,filter函数根据func作用在序列每个元素上返回的结果进行过滤操作,如果是True则保留,False则过滤。

这里举一个有意思的例子:

埃拉托色尼筛选法求素数:

In [58]: def _init_iter():#产生从3开始的无限序列
    ...:     n = 1
    ...:     while True:
    ...:         n = n +2
    ...:         yield n
    ...:

In [59]: def _not_divisable(n):#定义筛选函数,判断一个数是否可以被n整除,若可以整除,则返回True,否则返回False
    ...:     return lambda x:x%n > 0
    ...:
    ...:

In [60]: def primes():
    ...:     yield 2
    ...:     it = __init_iter()#产生一个无限奇数序列
    ...:     while True:
    ...:         n = next(it) #获得第一个素数
    ...:         yield n
    ...:         it = filter(_not_divisable(n), it)#筛选掉n的倍数


In [66]: for n in primes():
    ...:     if n<100:
    ...:         print(n)
    ...:     else:
    ...:         break
    ...:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

判断一个数是否是回文数(使用切片):

In [82]: def is_palindorme(n):
    ...:     n = str(n)
    ...:     if n == n[::-1]:
    ...:         return True
    ...:     else:
    ...:         return False
    ...:

In [85]: list(filter(is_palindorme, range(200)))
Out[85]:
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 11,
 22,
 33,
 44,
 55,
 66,
 77,
 88,
 99,
 101,
 111,
 121,
 131,
 141,
 151,
 161,
 171,
 181,
 191]

-- sorted(iterable, key)


sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

key指定的函数作用在iterable的每一个元素上,sorted按照key指定的函数进行排序。

该函数可以用于自定义的排序,默认的数字排序是从小到大,字母排序是按ASCII码排序。

In [98]: sorted([1,23,34,2,34,65,2])
Out[98]: [1, 2, 2, 23, 34, 34, 65]


In [100]: sorted([1,-23,34,2,-34,65,-2],key = abs)
Out[100]: [1, 2, -2, -23, 34, -34, 65]

猜你喜欢

转载自blog.csdn.net/qq_37653394/article/details/82955415