python higher-order functions - map / filter / sorted / reduce

高阶函数Is in a function, parameter transfer function , such function is called higher-order functions, it can be used to simplify the often complex operations.

  • map / filter / sorted are the Python 内置函数, can be used directly

the Map : a sequence of iterations

map()Function is a function of the reference sequence and, passing successively to the function of each element of the sequence and returns a new Iterator, it can list()function in the role of values, so that the result is returned list.

 def test(x):
     return x.upper()

 s = map(test, ['a', 'b', 'c'])

print (s)
<map at 0x7f11e540ceb8>

print (list(s))
['A', 'B', 'C']

filter : filtering a sequence

filter()It is a function of the reference sequence and function, the following functions and sequences anonymous 'abcd'. Passing successively to the function of each element of the sequence, the result is Truethat the element is returned, otherwise discarded. The return value is one Iterator, can use the list()function operates on the value, so that the result is returned list.

In [1]: result = filter(lambda x: x == 'a', 'abcd')

In [2]: result
Out[2]: <filter at 0x7f11ce77df60>

In [3]: list(result)
Out[3]: ['a']

sorted : for 可迭代对象sorting

See Python sort

reduce

reduceAnd the above three functions have different points, it is not built-in function, you need to import functoolsthe module can be used.
See python modules - functools

Guess you like

Origin blog.csdn.net/weixin_34336292/article/details/90993905
Recommended