Python split string in moving window
I have a开发者_运维问答 string with digits like so - digit = "7316717"
Now I want to split the string in such a way that the output is a moving window of 3 digits at a time. So I get -
["731", "316", "167", "671", "717"]
How would the approach be? Straightforward way is to put in for-loop and iterate. But I feel some inbuilt python string function can do this in less code. Know of any such approach?
The itertools examples provides the window
function that does just that:
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
Example usage:
>>> ["".join(x) for x in window("7316717", 3)]
['731', '316', '167', '671', '717']
>>> s = "7316717"
>>> [s[i:i+3] for i in range(len(s)-2)]
['731', '316', '167', '671', '717']
There is a very good recipe pairwise
in itertools docs.
Modernizing it a bit for n
elements in the group, I made this code:
from itertools import tee, izip
def window(iterable, n):
els = tee(iterable, n)
for i, el in enumerate(els):
for _ in xrange(i):
next(el, None)
return izip(*els)
print(["".join(i) for i in window("2316515618", 3)])
Python 2.7
digit = "7316717"
digit_sets = [digit[i:i+3] for i in range(len(digit)-2)]
Following Shawn's, the newest example of sliding window uses collections.deque:
def sliding_window(iterable, n):
# sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG
it = iter(iterable)
window = collections.deque(islice(it, n), maxlen=n)
if len(window) == n:
yield tuple(window)
for x in it:
window.append(x)
yield tuple(window)
精彩评论