Skip to content

Instantly share code, notes, and snippets.

@mattboehm
Created September 17, 2012 14:48
Show Gist options
  • Save mattboehm/3737809 to your computer and use it in GitHub Desktop.
Save mattboehm/3737809 to your computer and use it in GitHub Desktop.
import itertools
#ugly one-liner
def _ugly_split_at(pred, seq):
return list(itertools.ifilter(
None,
[
(
(seq[idx:idx+1] + list(itertools.takewhile(lambda x: not pred(x), seq[idx+1:])))
if idx == 0 or pred(el)
else []
)
for idx, el in enumerate(seq)
]
))
#iterable version
def _spliterator(pred, iterable):
iterable = iter(iterable)
try:
sublist = [iterable.next()]
except StopIteration:
return
for el in iterable:
if pred(el):
yield sublist
sublist = [el]
else:
sublist.append(el)
yield sublist
def test_split_methods():
pred = lambda x: len(x) == 1
l = ['foo', 'bar', 'a', 'baz', 'b', 'c', 'spam']
print _ugly_split_at(pred, l)
print _ugly_split_at(pred, [])
print list(_spliterator(pred, l))
print list(_spliterator(pred, (x for x in l))) #works with iterables
print list(_spliterator(pred, []))
if __name__ == '__main__':
test_split_methods()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment