Looking for a buffered/windowed iterator
Robert Kern
robert.kern at gmail.com
Mon Oct 12 12:50:26 EDT 2009
On 2009-10-12 11:21 AM, samwyse wrote:
> Previous discussions in c.l.py (primarily those that propose new
> functions to be added to itertools) claim that people do this all the
> time, but seem woefully short of actual examples. Before I possibly
> re-invent the wheel(*), could someone point me to some actual code
> that approximates what I want to do? Thanks.
From grin, my grep-alike:
http://pypi.python.org/pypi/grin
def sliding_window(seq, n):
""" Returns a sliding window (up to width n) over data from the iterable
Adapted from the itertools documentation.
s -> (s0,), (s0, s1), ... (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
it = iter(seq)
result = ()
for i, elem in itertools.izip(range(n), it):
result += (elem,)
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
A slight modification of this should get what you want.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list