Python basis: lambda anonymous function

format

lambda argument1, argument2,... argumentN : expression

square = lambda x: x**2
print(square(2))

And the difference between regular function

  Anonymous functions and lambda routine functions, are a function object returned (function object)
 
  lambda is an expression (expression), is not a statement (statement). Expressions can be evaluated, similar to the code "formula", and the statement was a complete certain functions of executable code.
  So, lambda can be used inside the list:
l = [(lambda x:x**2) (x) for x in range(10)]
print(list(l))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  Similarly, you can as parameters
= L [(. 1, 20 is), (. 3, 0), (. 9, 10), (2, -1 )] 
l.sort (Key = the lambda X: X [. 1]) # By List progenitor second Meta sorting elements 
Print (L) 
output 
[( 2, -1), (3, 0), (9, 10), (1, 20)]
  Body lambda expression is a simple one-line, and can not be extended to a multi-line block.

The code can be simplified using lambda

squared = map(lambda x: x**2, [1, 2, 3, 4, 5])
print(list(squared))

  Above that code, if not conventional lambda expressions and functions:

def squared2(x):
    return x[1] if isinstance(x,tuple) else x**2

squared = map(squared2, [1, 2, 3, 4, 5,(1,3)])
print(list(squared))

Python Functional Programming

  Python programming function has three basic functions map (), reduce (), filter ()

  map(function, iterable [,iterable2])

  map traversal iterables taken elements sequentially passed as a parameter function function, for example: each element is increased twice

l = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, l) # [2, 4, 6, 8, 10]

  filter(function, iterable)

  and filter map as iterables traversal, and sequentially pass function, except that, each filter function determines the result is True or False, the result is a composition of a listing of elements return True

  Example: Returns a list of all even

l = [1, 2, 3, 4, 5]
new_list = filter(lambda x: x % 2 == 0, l) # [2, 4]

  reduce(function, iterable[, initializer])

  Wherein the target function is a function, which has two predetermined parameters, expressed in iterable each element and the results of the last call, using the calculation function, the final returns a single value.

  Source cooperate reduce understand:

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

  Example accumulated elements in the list

from functools import reduce
l = [1,2,3,4,5]
result = reduce(lambda x,y:x+y, l )
print(result) #15
result = reduce(lambda x,y:x+y, l,10 )
print(result) #25

Questions

  The dictionary d = { 'mike': 10, 'lucy': 2, 'ben': 30} sorted in descending value

d = {'mike': 10, 'lucy': 2, 'ben': 30}
d = sorted(d.items(), key=lambda x: x[1],reverse = True ) #[('ben', 30), ('mike', 10), ('lucy', 2)]
d = dict(d)
print(d)

 reference:

Geek Time "Python core technology and practical"

 

Guess you like

Origin www.cnblogs.com/xiaoguanqiu/p/10958623.html