6

Function Decorator, Map/Filter/Reduce in Python

 2 years ago
source link: https://jyzhu.top/2021/10/25/Function-Decorator-Map-Filter-Reduce-in-Python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Function Decorator, Map/Filter/Reduce in Python

发表于

2021-10-25 分类于 Computer Notes

阅读量: 2 Valine: 0

Function

Function Decorator

def track(fn):
def h(x):
print('the fn {} has x {}'.format(fn, x))
return fn(x)
return h

@track
def foo(x):
return x ** x

print(foo(3))

decorator equals to: foo = track(foo)

Lambda

     lambda            x            :          f(g(x))
"A function that takes x and returns f(g(x))"

Map will apply the function on elements in the iterables one by one, and return a map object (iterable).

map(func, *iterables)
  • how many parameters the func require, how many iterables there are.
  • whenever one iterable reaches its end, the map will stop without an error.
  • map will return a map object. use list() to convert it to a list.

Filter

Filter passes each element in the iterable to the function, and if the function returns True, the element will be returned.

filter(func, iterable)
  • the func should require one parameter, and return boolean type.
  • unlike map, only one iterable is supported.
  • if the func doesn't return a boolean type, the filter simply returns the iterable itself.
  • also use list() to convert the filter object to a list.

Reduce

Reduce takes the 1st and 2nd elements in the iterable, put them into the func, and take the return of the func and the 3rd element in the iterable, put them into the func again...

from functools import reduce
reduce(func, interable[, initial])
  • initial is literally an initial input into the func.

其他发布渠道


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK