Python : lambda

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions.

Lambdas

  • lambda expression
lambda_expr ::= “lambda” [parameter_list]: expression 
lambda_expr_nocond ::= “lambda” [parameter_list]: expression_nocond

Lambda expressions are used to create anonymous functions. The expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with:

def <lambda>(arguments):
    return expression

for example

  • 1
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)    #   f(x) = x+42
>>> f(0)
42
>>> f(1)
43
  • 2
>>> f = lambda x,y: x+y
>>> f(2,3)
5
  • 3
>>> f = lambda: 2+3            # 无参 lambda
<function <lambda> at 0x7f1c6a48cbf8>
>>> f()
5

reduce

  • functools.reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of 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). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.
Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value
  • for example
>>> import functools
>>> a = [1,2,3,4]
>>> functools.reduce(lambda x,y: x+y, a, 10)
20
>>> functools.reduce(lambda x,y: x+y, a)
10

Map

Return an iterator that applies function to every item of iterable, yielding the results.

>>> def multiply(x):
...     return (x*x)
... 
>>> def add(x):
...     return (x+x)
... 
>>> funcs = [multiply, add]
>>> for i in range(5):
...     value = list(map(lambda x: x(i), funcs))
...     print(value)
... 
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]

filter

  • filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that

filter(function, iterable)

is equivalent to the generator expression

(item for item in iterable if function(item))`

if function is not None and

(item for item in iterable if item) 

if function is None.

  • for example,
>>> a = range(-5,5)
>>> list(filter(lambda x: x<0, a))
[-5, -4, -3, -2, -1]
>>> 
>>> list(filter(None, a))
[-5, -4, -3, -2, -1, 1, 2, 3, 4]            # 没有 0 
  • itertools.filterfalse(predicate, iterable)

Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Roughly equivalent to:

def filterfalse(predicate, iterable):
    if predicate is None:
        predicate = bool
    for x in iterable:
        if not predicate(x):
            yield x

for example,

>>> list(itertools.filterfalse(lambda x:x%2, range(10)))
[0, 2, 4, 6, 8]
>>>
>>> list(itertools.filterfalse(None, range(-2,2)))
[0]

read more

  • Python tips: Map, Filter and Reduce
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容