Python uses lambda functionsLearning Resources
- Lambda function Learning
- List comprehension
- Multidimensional array Initialization
Lambda functions
Python supports an interesting syntax that allows you to quickly define the minimum function for a single line. These functions, called Lambda, are borrowed from Lisp and can be used wherever functions are needed.
def f(x): return x*2
, replace with a lambda function can be written as: g = lambda x: x*2`
g (3) The result is 6 .
(lambda x:x*2) (3) ' is the same effect.
- This is a lambda function that accomplishes the same thing as the normal function above. Note the short syntax here: there is no parentheses around the argument list, and the return keyword is omitted (implied, because the entire function has only one row). Moreover, the function does not have a function name, but it can be assigned to a variable for invocation
- You don't even need to assign a value to a variable when you use a lambda function. This may not be the most useful thing in the world, it just shows that the lambda function is just an inline function.
- In general, a lambda function can receive any number of arguments (including optional parameters) and return the value of a single expression. A lambda function cannot contain commands and cannot contain more than one expression. Do not attempt to cram too much into the lambda function; If you need something more complicated, you should define a normal function, and then you want to make it long enough.
我将它们用在需要封装特殊的、非重用代码上,避免令我的代码充斥着大量单行函数。
List derivation (listing comprehension)
See a simple code
Testlist = [1,2,3,4]
def mul2 (x):
Print x*2
[Mul2 (i) for I in Testlist]
[Mul2 (i) for i in Testlist if i%2==0]
Multidimensional array Initialization
multilist = [[0 for col in range(5)] for row in range(3)]
Apply
m = [[ -1.0, 2.0/c-1, -2.0/c+1, 1.0], [2.0, -3.0/c+1, 3.0/c-2, -1.0], [ -1.0, 0.0, 1.0, 0.0], [0.0, 1.0/c, 0.0, 0.0]]multiply = Lambda x:x*cm = [[Multiply (M[col][row]) for Col in Range (4)] for row in range (4)]print [[M[col][row] for Col in range (4)] to row in range (4)]
The work it does: M is a matrix that contains the parameter C, and he calculates the results of the C*m
Thought for a moment, and the last sentence changed to
print [[multiply(each) for each in row] for row in m]
More Pythonic
Python uses lambda functions and list comprehension