split¶
- class iteration_utilities.split(iterable, key, maxsplit=-1, keep=False, keep_before=False, keep_after=False, eq=False)¶
Splits an iterable by a key function or delimiter.
- Parameters:
- iterableiterable
The iterable to split.
- keycallable
The function by which to split the iterable (split where
key(item) == True
).- maxsplit
int
, optional The number of maximal splits. If
maxsplit=-1
then there is no limit. Default is-1
.- keep
bool
If
True
also include the items wherekey(item)=True
as separate list. Default isFalse
.- keep_before
bool
If
True
also include the items wherekey(item)=True
in the list before splitting. Default isFalse
.- keep_after
bool
If
True
also include the items wherekey(item)=True
as first item in the list after splitting. Default isFalse
.- eq
bool
If
True
split the iterable wherekey == item
instead ofkey(item) == True
. This can significantly speed up the function if a single delimiter is used. Default isFalse
.
- Returns:
- splitted_iterablegenerator
Generator containing the splitted iterable (lists).
- Raises:
- TypeError
If
maxsplit
is smaller than-2
. If more than one of thekeep
arguments isTrue
.
Examples
>>> from iteration_utilities import split >>> list(split(range(1, 10), lambda x: x%3==0)) [[1, 2], [4, 5], [7, 8]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep=True)) [[1, 2], [3], [4, 5], [6], [7, 8], [9]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep_before=True)) [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep_after=True)) [[1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> list(split(range(1, 10), lambda x: x%3==0, maxsplit=1)) [[1, 2], [4, 5, 6, 7, 8, 9]]
>>> list(split([1,2,3,4,5,3,7,8,3], 3, eq=True)) [[1, 2], [4, 5], [7, 8]]
- keep_after¶
(
bool
) Keep the delimiter as first item of the next group (readonly).New in version 0.6.
- keep_before¶
(
bool
) Keep the delimiter as last item of the last group (readonly).New in version 0.6.
- key¶
(callable or any type) The function or value by which to split (readonly).
New in version 0.6.