Functional Programming Python learning

  Functional Programming 1

  1.1 anonymous function

  Keyword lambda represents the anonymous function, before the colon x represents parameters. There can be only one expression after the colon, do not write return, the return value is the result of the expression. You do not have to define the function name directly create a function object. Return function, you can also return anonymous function. The following code is an example:

  myabs = lambda x : -x if x < 0 else x

  myabs(-2)

  Output is as follows:

  2

  1.2 return function

  Python function can only return int, str, list, dict data types, functions can also return!

  For example, the definition of a function f (), we return it to a function g, can be written like this:

  def f():

  print('call f()...')

  def g (): # define the function g

  print('call g()...')

  return g # return function g ()

  In the above code function f () also defined inside a function g (). Since the function g () is an object, function name g () is the variable to point to the function g (), so the outermost layer of the function f () can return a variable g (), that is, the function g () itself. Call the function f (), we get f () function returns a:

  x = f () # call f ()

  Output is as follows:

  call f()...

  1.3 Closures

  Functions and external functions defined inside the function definition is the same, but they can not be accessed outside:

  def g (): # define the function g

  print('call g()...')

  def f():

  print('call f()...')

  return g # return function g ()

  The g () into the definition of function f () inside, to prevent other code calls g ():

  def f():

  print('call f()...')

  def g (): # define the function g

  print('call g()...')

  return g # return function g ()

  This inner layer functions as a variable reference function layer (also considered a variable parameter), and then return to the situation of the inner function, called closure Closure. Characteristics of closure is also a function returns a reference to a local variable outer function. Therefore, to correctly use a closure, it is necessary to ensure that a local variable refers can not be changed after the function returns.

  1.4 partial function

  int () function to convert the string to be an integer. Only when an incoming string, int () function default decimal conversion:

  int('98')

  Output is as follows:

  98

  Base function also provides additional parameters, the default value is 10. If the incoming base parameters, you can do the N-ary conversion:

  int('100', base = 8)

  Output is as follows:

  64

  functools.partial is to create a partial function, use the following code to create a new function:

  import functools

  int2 = functools.partial(int, base = 2)

  int2 ( '1000')

  Output is as follows:

  8 Wuxi gynecological hospital http://www.ytsgfk120.com/

  functools.partial can be a function of many parameters become less of a new parameter function, fewer parameters need to specify default values ​​when creating difficulty function call is reduced.

  1.5 reduce function

  Use reduce (), reduce the need to import the package functools:

  from functools import reduce

  received parameter reduce function () is a function f and a list, f must receive two parameters. reduce () for each element of the list of frequently called function f, and returns the final result value.

  The following is a function f:

  def f(x, y):

  return x + y

  Call reduce (f, [1, 3, 5, 7, 9]) when, reduce the function is calculated as follows:

  First calculate the first two elements: f (1, 3), the result is 4;

  And then the results of the third element is calculated: f (4, 5), the result is 9;

  And then the results of the fourth element is calculated: f (9, 7), the result is 16;

  5 and sends the results of element calculation: f (16, 9), was 25.

  reduce () may also receive a third optional parameter, calculated as the initial value. If the initial value of 100, calculated: reduce (f, [1, 3, 5, 7, 9], 100), the result becomes 125, as is first round of calculation: calculating an initial value of the first element : f (100, 1), the result is 101.

  1.6 filter function

  filter () function accepts a function f and a list. Effect function f is determined for each element, returns True or False. filter () filter based on the determination result does not conform to the conditions of the element, and returns the new list of qualified elements.

  From a list [1, 4, 6, 7, 9, 12, 17] to remove an even number, odd retention, first, a determination function to write odd:

  def is_odd(x):

  return x % 2 == 1

  Then using the filter () function to filter out the even:

  list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

  Output is as follows:

  [1, 7, 9, 17]

  Use filter (), you can perform many useful functions. For example, deleting None or the empty string. The following is a code for determining whether a function string is empty:

  def is_not_empty(s):

  return s and len(s.strip()) > 0

  Then enter:

  list(filter(is_not_empty, ['test', None, '', ' ', 'END']))

  The output is:

  ['test', 'END']

  2 Python learning point to note

  1, instead of Null None NULL;

  2, True or False the first letter should be capitalized;

  3, print () prints each string in turn, encounters a comma, then, will output a space. The following code is an example:

  print('A', 'B')

  Output is as follows:

  A B

  4, Python to 0, the empty string '' and None as False, and other values ​​are non-empty string as True.


Guess you like

Origin blog.51cto.com/14503791/2431280