Skip to content

Commit 18a1b82

Browse files
committed
itertoolz: Add split to segment a sequence around an index.
1 parent c95cf7d commit 18a1b82

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

toolz/itertoolz.py

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@
1010

1111

1212
__all__ = ('remove', 'accumulate', 'groupby', 'merge_sorted', 'interleave',
13-
'unique', 'isiterable', 'isdistinct', 'take', 'drop', 'take_nth',
14-
'first', 'second', 'nth', 'last', 'get', 'concat', 'concatv',
15-
'mapcat', 'cons', 'interpose', 'frequencies', 'reduceby', 'iterate',
16-
'sliding_window', 'partition', 'partition_all', 'count', 'pluck',
17-
'join', 'tail', 'diff', 'topk', 'peek', 'random_sample')
13+
'unique', 'isiterable', 'isdistinct', 'take', 'drop', 'split',
14+
'take_nth', 'first', 'second', 'nth', 'last', 'get', 'concat',
15+
'concatv', 'mapcat', 'cons', 'interpose', 'frequencies',
16+
'reduceby', 'iterate', 'sliding_window', 'partition',
17+
'partition_all', 'count', 'pluck', 'join', 'tail', 'diff',
18+
'topk', 'peek', 'random_sample')
1819

1920

2021
def remove(predicate, seq):
@@ -350,6 +351,27 @@ def drop(n, seq):
350351
return itertools.islice(seq, n, None)
351352

352353

354+
def split(n, seq):
355+
""" Splits the sequence around element n.
356+
357+
>>> list(map(tuple, split(2, [10, 20, 30, 40, 50])))
358+
[(10, 20), (30,), (40, 50)]
359+
360+
See Also:
361+
take
362+
nth
363+
drop
364+
"""
365+
366+
front, middle, back = itertools.tee(seq, 3)
367+
368+
front = itertools.islice(front, 0, n)
369+
middle = itertools.islice(middle, n, n + 1)
370+
back = itertools.islice(back, n + 1, None)
371+
372+
return front, middle, back
373+
374+
353375
def take_nth(n, seq):
354376
""" Every nth item in seq
355377

0 commit comments

Comments
 (0)