Created
April 23, 2012 22:55
-
-
Save agfor/2474395 to your computer and use it in GitHub Desktop.
A few extra itertools-esque snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
import itertools | |
def last(iterable, deque=collections.deque): | |
return deque(iterable, maxlen = 1)[0] | |
def iterlen(iterable): | |
return sum(1 for _ in iterable) | |
def droptake(iterable, takecondition, dropcondition = None, | |
takewhile = itertools.takewhile, dropwhile = itertools.dropwhile): | |
return takewhile(dropwhile(iterable, | |
dropcondition or (lambda item: not takecondition(item))), takecondition) | |
def prepend(iterable, *items): | |
for item in itertools.chain(items, iterable): | |
yield item | |
def append(iterable, *items): | |
for item in itertools.chain(iterable, items): | |
yield item | |
def skip(iterable, at_start=0, at_end=0): | |
it = iter(iterable) | |
for x in itertools.islice(it, at_start): | |
pass | |
if not at_end: | |
return it | |
queue = collections.deque(itertools.islice(it, at_end), at_end + 1) | |
return (queue.append(x) or queue[0] for x in it) | |
def reduceself(func, obj, times): | |
return reduce((lambda (ob, _): func(ob)), range(times), obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment