5 Functions

5.4 Lambda expressions

  • Lambda expressions often declare anonymous functions,
    • That is, a small function that is temporarily used without a function name,
    • Temporarily want a function similar to a function but do not want to define a function.
  • The key parameter of sorted () and list method sort (),
    • The first parameter of the built-in functions map () and filter ()
  • Lambda expressions can only contain one expression, other complex statements are not allowed,
    • But other functions can be called in the expression,
    • The calculation result of this expression is equivalent to the return value of the function.

Insert picture description here

Insert picture description here

  • When using lambda expressions, pay attention to the problems that variable scope may bring.
  • In the following code, the variable x is defined in the outer scope, and is not a local variable for the lambda expression, so it is wrong.

Insert picture description here

Insert picture description here

  • Lambda expression is equivalent to a function with only one return
  • The true return value when called depends on the current value of the global variable i.

Insert picture description here

  • Lambda expression is very convenient to define some small functions
  • If you only need a simple operation, try to use the functions provided in the standard library operator
    • Avoid defining lambda expressions yourself,
    • The functions in operator are more efficient

5.5 Essentials of generator function design

Published 589 original articles · 300 praises · 80,000 + views

Guess you like

Origin blog.csdn.net/zhoutianzi12/article/details/105572438