Miscellaneous
Filter — Map — Reduce
filter function
filter(function, iterable) constructs an iterator from those elements of iterable for which function returns True.
iterablemay be a sequence, any container that supports iteration, or an iterator- If
functionisNone, the identity predicate is assumed and all falsy elements are removed
Example:
import numpy as np
array = np.arange(1, 10, dtype=int)
filtered_array = filter(lambda x: x > 3, array)
print(list(filtered_array))
Output:
[4, 5, 6, 7, 8, 9]
map function
map(function, iterable, ...) returns an iterator that applies function to every item of iterable, yielding the results.
- If additional
iterablearguments are provided,functionmust accept that many arguments and is applied to items from all iterables in parallel - With multiple iterables, the iterator stops when the shortest iterable is exhausted
Example:
import math
mapped_array = map(np.sqrt, array)
print(list(mapped_array))
Output:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]
reduce function
functools.reduce(function, iterable[, initializer]) applies function of two arguments cumulatively to the items of iterable, from left to right, thereby reducing the iterable to a single value.
- If
initializeris present, it is used as the initial accumulator and is placed before the items of the iterable - If
initializeris not given anditerablecontains only one item, that single item is returned
Example:
from functools import reduce
def reduction_function(x, y):
print("X:", x, "Y:", y)
return x + y
reduce(reduction_function, array)
Output (example):
X: 1 Y: 2
X: 3 Y: 3
X: 6 Y: 4
X: 10 Y: 5
X: 15 Y: 6
X: 21 Y: 7
X: 28 Y: 8
X: 36 Y: 9
45