Welcome to follow my wechat official account AlwaysBeta, more exciting content waiting for you.

lambda

Lambda is a keyword that exists in many languages. In short, it can achieve the function creation function.

Here are two ways lambda can be used.

func1 = lambda : <expression()>
func2 = lambda x : <expression(x)>
func3 = lambda x,y : <expression(x,y)>
Copy the code

In the first statement, lambda creates a function func1 with no arguments. This is the same as creating a function using def below.

def func1(a):
    <expression()>
Copy the code

In the second and third statements, lambda creates a function func2 that takes one argument and a function func3 that takes two arguments, respectively. This is the same as creating a function using def below.

def func2(x):
    <expression(x)>

def func3(x,y):
    <expression(x,y)>
Copy the code

It is important to note that when func1 is called, it does not take an argument, but it must have parentheses (); otherwise it returns the definition of the function, not the result of its execution.

>>> func = lambda : 123
>>> func
<function <lambda> at 0x100f4e1b8>
>>> func()
123
Copy the code

Also, although the lambda created function is assigned to a function name in each of the above examples, this is not required. As you can see from the example below, many times we call functions created by lambda directly without naming a function, which is where we often hear about anonymous functions.

map()

A common call to the map() function looks like this:

map(func, iterable)
Copy the code

Map () takes two mandatory arguments, the first a function name and the second an iterable object such as a list, tuple, and so on.

Map () simply passes each element of the second argument (iterable) to the first argument (func), executes the function in turn, and returns the result as a new list object. The return result is always a list.

A simple example is as follows:

>>> double_func = lambda s : s * 2
>>> map(double_func, [1.2.3.4.5[])2.4.6.8.10]
Copy the code

In addition to the common pattern of passing in one iterable, map() supports passing in multiple iterables.

map(func, iterable1, iterable2)
Copy the code

In the case of multiple iterables, map() takes one element in turn from all iterables, forming a list of tuples, and passes the tuples in turn to func; If the length of the iterable is inconsistent, None is used to fill it up.

The following example should make it easier to understand.

>>> plus = lambda x,y : (x or 0) + (y or 0)
>>> map(plus, [1.2.3], [4.5.6[])5.7.9]
>>> map(plus, [1.2.3.4], [4.5.6[])5.7.9.4]
>>> map(plus, [1.2.3], [4.5.6.7[])5.7.9.7]
Copy the code

In the example above, the form x or 0 is used to prevent None + int from being an exception.

Note that the number of iterables should be the same as the number of func arguments, otherwise an exception will occur because the number of arguments passed is not the same as the number of function arguments, which should be understandable.

>>> plus = lambda x,y : x + y
>>> map(plus, [1.2.3])
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
TypeError: <lambda>() takes exactly 2 arguments (1 given)
Copy the code

There is also a special case of map() where func is None. At this point, map() still takes one element from each iterable, forms a tuple list, and returns that tuple list as a result.

>>> map(None[1.2.3.4[])1.2.3.4]
>>> map(None[1.2.3.4], [5.6.7.8[(])1.5), (2.6), (3.7), (4.8)]
>>> map(None[1.2.3.4], [5.6.7[(])1.5), (2.6), (3.7), (4.None)]
>>> map(None[1.2.3.4], [6.7.8.9], [11.12[(])1.6.11), (2.7.12), (3.8.None), (4.9.None)]
Copy the code

reduce()

The reduce() function is called as follows:

reduce(func, iterable[, initializer])
Copy the code

The reduce() function accumulates the elements of an iterable from left to right, resulting in a number. The third parameter, initializer, is the initial value and can be empty. If empty is None, we start with the second element of the iterable and take the first element as the result of the previous one.

The text description may not be clear, but the reduce() source code should make it clear.

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        try:
            initializer = next(it)
        except StopIteration:
            raise TypeError('reduce() of empty sequence with no initial value')
    accum_value = initializer
    for x in it:
        accum_value = function(accum_value, x)
    return accum_value
Copy the code

Add in the following example, and you should have a grasp of reduce() functionality.

>>> plus = lambda x, y : x + y
>>> reduce(plus, [1.2.3.4.5])
15
>>> reduce(plus, [1.2.3.4.5].10)
25
Copy the code

filter()

The filter() function is called as follows:

filter(func, iterable)
Copy the code

Filter () takes only two arguments, the first being a function name and the second an iterable object, such as a list, tuple, and so on.

The filter() function is called in the same way as map(). Each element in the second argument (iterable) is passed to the first argument (func). The difference is that filter() determines the bool value of each execution and only filters out bool values true to form a new list and return it.

>>> mode2 = lambda x : x % 2
>>> filter(mode2, [1.2.3.4.5.6.7.8.9.10[])1.3.5.7.9]
Copy the code

zip()

The zip() function is called as follows:

zip([iterable, ...] )Copy the code

The zip() function takes one or more iterable objects, packs the corresponding elements of the object into tuples, and returns a list of those tuples.

>>> zip([1.2.3], ["a"."b"."c"[(])1.'a'), (2.'b'), (3.'c')]
>>> dict(zip([1.2.3], ["a"."b"."c"]) {1: 'a'.2: 'b'.3: 'c'}
>>> dict(zip([1.2.3], ["a"."b"]) {1: 'a'.2: 'b'}
Copy the code

The number of packed tuples is the same as the number of shortest lists.

enumerate()

The enumerate() function is called in the following form:

enumerate(iterable, [start=0])
Copy the code

The enumerate() function is used to combine an iterable data object (such as a list, tuple, or string) into an index sequence that lists both data and data subscripts, typically used in a for loop.

>>> enumerate(['Spring'.'Summer'.'Fall'.'Winter'])
<enumerate object at 0x1031780>
>>> list(enumerate(['Spring'.'Summer'.'Fall'.'Winter'[(]))0.'Spring'), (1.'Summer'), (2.'Fall'), (3.'Winter')]
Copy the code

All (), any ()

The all() and any() functions are called as follows:

all(iterable)
any(iterable)
Copy the code

These two functions are relatively simple, which determine whether an iterable is all True or has True.

>>> all([0.1.2])
False
>>> any([0.1.2])
True
Copy the code




Related documents:

zhuanlan.zhihu.com/p/23384430

Coolshell. Cn/articles / 10…

Debugtalk.com/post/python…