iterating a span of a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: iterating a span of a list (/thread-23408.html) |
iterating a span of a list - Skaperen - Dec-29-2019 i'm looking for something that can do like this span() function can:a = ['foo','bar','boo','far','baz'] for b in span(a,3): print(*b) a = [1,2,3,4,5,6,7,8,9] for b in span(a,4): print(*b) this shouldn't be hard to code, but if zip() exists, maybe something like this span() exists. if it would return an iterator, that would be fine.
RE: iterating a span of a list - Gribouillis - Dec-29-2019 It looks like more_itertools.windowed()
RE: iterating a span of a list - Skaperen - Dec-29-2019 implementing it was next to trivial. a slice in a comprehension. def span(s,n): return iter([s[x:x+n]for x in range(len(s)-n+1)]) RE: iterating a span of a list - DeaD_EyE - Dec-29-2019 import itertools from functools import partial def window(sequence, window_size, uncomplete=True, fillvalue=None): if uncomplete: izip = partial(itertools.zip_longest, fillvalue=fillvalue) else: izip = zip yield from izip(*[iter(sequence)] * window_size) l = list(range(10)) for chunk in window(l, 3): print(chunk) If you use uncomplete=False , the zip function will be used.The zip function stops iterating, if there are not enough values, to fill the window. l = list(range(10)) for chunk in window(l, 3, uncomplete=False): print(chunk)
RE: iterating a span of a list - Gribouillis - Dec-29-2019 The more_itertools implementation uses a deque, but it works with any iterable, not only iterables with random access. @DeaD_EyE I think your function does something different. RE: iterating a span of a list - Skaperen - Dec-29-2019 yes, DeaD_EyE's result is different. |