flat_map_depth()
Recursively flat maps a given collection up to the given depth. This is similar to :func:`flat_map`, but will continue to flatten the mapped results until they are no longer iterable up to the given depth.
Implementation
Args: collection: Collection to iterate over. func: Iteratee applied per iteration. depth: Maximum recursion depth. Returns: Fully flattened mapped list up to the given depth.
Example
nested = lambda x: [[x, x], [x, x]]
flat_map_depth([1, 2], nested, 2)
Expected output: [1, 1, 1, 1, 2, 2, 2, 2]
Source Code
def flat_map_depth(
collection: List[Any], func: Callable[[Any], List[Any]], depth: int
) -> List[Any]:
result = flat_map(collection, func)
def _flatten(arr: Any, d: int) -> List[Any]:
"""
Recursively flattens a list or tuple up to the given depth.
Args:
arr: The list or tuple to flatten.
d: The maximum recursion depth.
Returns:
A flattened list of elements.
Examples:
>>> _flatten([1, 2], 2)
[1, 1, 1, 1, 2, 2, 2, 2]
"""
if d <= 0 or not isinstance(arr, (list, tuple)):
return [arr]
out: List[Any] = []
for y in arr:
if isinstance(y, (list, tuple)):
out.extend(_flatten(y, d - 1))
else:
out.append(y)
return out
return _flatten(result, depth)