Lambda
"lambda arguments: expression" equals to "function"
- arguments: Input values to the function.
- expression: The single operation or computation performed on the arguments. The result of this expression is the function's return value.
Simple usage
def add(x, y):
return x + y
add_lambda = lambda x, y: x + y
print(add(3, 4))
print(add_lambda(3, 4))
Combined with map
pairs = [(1, 2), (3, 4), (5, 6)]
sums = list(map(lambda pair: pair[0] + pair[1], pairs))
print(sums)
Reduce
""" from python functools.py
reduce(function, iterable[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence
or iterable, from left to right, so as to reduce the iterable to a single
value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the iterable in the calculation, and serves as a default when the
iterable is empty.
"""
it = iter(sequence)
if initial is _initial_missing:
try:
value = next(it)
except StopIteration:
raise TypeError(
"reduce() of empty iterable with no initial value") from None
else:
value = initial
for element in it:
value = function(value, element)
return value
Simple usage
from functools import reduce
from operator import mul
axial_shape = (64, 64)
self.max_seq_len = reduce(mul, axial_shape, 1)
nums = [3, 1, 7, 9, 2]
result = reduce(lambda x, y: x if x > y else y, nums)
print(result)
from functools import reduce
nested_list = [[1, 2], [3, 4], [5, 6]]
result = reduce(lambda x, y: x + y, nested_list)
print(result)