In Python, one-liner is hard to do, but it's not impossible. I think that the reason why one-liner is difficult to do in Python is that there are few things that can be expressed and that compound sentences cannot be written in one line. Here, we will introduce a method for incorporating various processes into an expression.
ʻIf a: f () can be written as ʻa and f ()
. ʻIf not a: f () can be written as ʻa or f ()
.
(If you are not familiar with the short circuit of logical operators, please see http://qiita.com/gyu-don/items/a0aed0f94b8b35c43290.)
Also, the ternary operator has a slightly unpleasant syntax. true_value if condition else false_value
You can combine multiple expressions into one expression by creating tuples and lists. You can also retrieve the value at a specific location by referring to it with [0] or [-1] at the end.
Loops are written in list comprehensions.
Especially in Python3, generator objects appear everywhere. The difference between a list and a generator is important, especially when you're expecting side effects. List comprehensions create a list up to the last element on the fly. On the other hand, the generator does not evaluate each element until it is called by next (). To evaluate each element, you can either call next yourself, do something like list (gen), or use the list comprehension for ... in.
lambda You can create anonymous functions with lambda, but in Python you can only create anonymous functions with a single expression.
You can use lambda to bind a variable without making a statement. Please use it in situations where it is difficult to use a semicolon.
(lambda a, b: a + b) (f (), g ())
realizes ʻa = f (); b = g (); a + b` in the expression.
In Python, assignments are statements, but in list.append they are expressions. It may be useful to have a list as an argument.
Example: An expression that returns the result of addition between 0 and 100 without using sum or reduce
(lambda t: [t.append(t.pop()+x)or t[0] for x in range(101)][-1])([0])
You don't have to make a complicated Y combinator, you just need the function to have an argument to receive itself.
Example: Factorial 1-10
(lambda f: f(10,f))(lambda n,f: n*f(n-1,f) if n>0 else 1)
end.
Recommended Posts