|
Python has built-in interesting but useful functions that fully reflect the charm of Python!
Filter (function, sequence ):Execute function (item) in sequence for items in sequence, and combine items with the execution result of true into a list/string/tuple (depending on the sequence type) to return:
>>> Def f (x): Return X % 2! = 0 and X % 3! = 0 >>> Filter (F, range (2, 25 )) [5, 7, 11, 13, 17, 19, 23]
>>> Def f (x): Return X! = 'A' >>> Filter (F, "abcdef ") 'Bcdef'
Map (function, sequence ):Execute function (item) in sequence for items in sequence. See the execution result to form a list and return:
>>> Def cube (x): Return x * x >>> Map (cube, range (1, 11 )) [1, 8, 27, 64,125,216,343,512,729,100 0]
>>> Def cube (x): Return x + x ... >>> Map (cube, "ABCDE ") ['A', 'bb ', 'cc', 'dd', 'ee']
In addition, MAP also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
>>> Def add (x, y): Return x + y >>> Map (ADD, range (8), range (8 )) [0, 2, 4, 6, 8, 10, 12, 14]
Reduce (function, sequence, starting_value ):Call the function sequentially for items in sequence. If starting_value exists, it can also be called as an initial value. For example, it can be used to sum the list:
>>> Def add (x, y): Return x + y >>> Reduce (ADD, range (1, 11 )) 55 (Note: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)
>>> Reduce (ADD, range (1, 11), 20) 75 (Note: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 20)
lambda: This is an interesting syntax supported by python, it allows you to quickly define the smallest function of a single row, similar to Macros in C language. These Lambda functions are borrowed from lisp and can be used in any function that requires them: >> G = Lambda X: x * 2 >> G (3) 6 >>> (lambda X: x * 2) (3) 6
|