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=-1then there is no limit. Default is-1.- keep
bool If
Truealso include the items wherekey(item)=Trueas separate list. Default isFalse.- keep_before
bool If
Truealso include the items wherekey(item)=Truein the list before splitting. Default isFalse.- keep_after
bool If
Truealso include the items wherekey(item)=Trueas first item in the list after splitting. Default isFalse.- eq
bool If
Truesplit the iterable wherekey == iteminstead 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
maxsplitis smaller than-2. If more than one of thekeeparguments 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).Added in version 0.6.
- keep_before¶
(
bool) Keep the delimiter as last item of the last group (readonly).Added in version 0.6.
- key¶
(callable or any type) The function or value by which to split (readonly).
Added in version 0.6.