chicken_turtle_util.iterable¶
Utility functions for working with iterables. sliding_window, ...
See also¶
itertools more_itertools
flatten |
Flatten shallowly zero or more times |
is_sorted |
Get whether iterable is sorted ascendingly |
partition |
Split iterable into partitions |
sliding_window |
Iterate using a sliding window |
-
chicken_turtle_util.iterable.
flatten
(iterable, times=1)[source]¶ Flatten shallowly zero or more times
Does not flatten str and bytes. Order is stably maintained (i.e. no 2 items swap places, even if they’re equal).
Parameters: iterable : iterable(any) except str or bytes
Iterable to flatten. May be any iterable other than str or bytes. May have irregular depth.
times : int, optional
The number of times to flatten shallowly or, equivalently, the number of levels of depth to remove. Should be 0 or more.
Yields: any
Items of iterable flattened to depth
depth(iterable) - times
Raises: ValueError
If input is invalid.
Examples
>>> list(flatten([[2, 3], 1, [5, [7, 8]]])) [2, 3, 1, 5, [7, 8]]
>>> list(flatten([[2, 3], 1, [5, [7, 8]]], times=2)) [2, 3, 1, 5, 7, 8]
>>> list(flatten([[2, 3], 1, [5, [7, 8]]], times=3)) [2, 3, 1, 5, 7, 8]
>>> flatten([iter([2, 3]), 1, [5, iter([7, 8])]]) iter([2, 3, 1, 5, iter([7, 8])])
>>> list(flatten([[2, 3], 1, [5, [7, 8]]], times=0)) [[2, 3], 1, [5, [7, 8]]]
-
chicken_turtle_util.iterable.
is_sorted
(iterable)[source]¶ Get whether iterable is sorted ascendingly
Parameters: iterable : iterable(comparable)
Iterable whose ordering to check
Returns: bool
Whether iterable is sorted
-
chicken_turtle_util.iterable.
partition
(iterable, key)[source]¶ Split iterable into partitions
Parameters: iterable : iterable(item :: any)
Iterable to split into partitions
key : (item :: any) -> (partition_id :: any)
Function that assigns an item of the iterable to a partition
Returns: partitioning : {(partition_id :: any)
Partitioning. Ordering of items is maintained within each partition. I.e. each partition is a subsequence of iterable.
-
chicken_turtle_util.iterable.
sliding_window
(iterable, size=2)[source]¶ Iterate using a sliding window
Parameters: iterable : iterable(any)
Iterable to slide a window across
size : int, optional
Window size
Yields: (any, ...)
Iterator slices of size size, taken from start to end through the iterator.
Raises: ValueError
When
ilen(iterable) < size or size < 1
See also
more_itertools.chunked
- Divide iterable into (non-overlapping) chunks of given size
Examples
>>> list(sliding_window(range(4))) [(0,1), (1,2), (2,3)]
>>> list(sliding_window(range(4), size=3)) [(0,1,2), (1,2,3)]
>>> list(sliding_window(range(1))) []