Python在移动窗口中拆分字符串 [英] Python split string in moving window

查看:49
本文介绍了Python在移动窗口中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数字字符串 - digit = "7316717"

现在我想以这样的方式拆分字符串,即输出是一次 3 位数的移动窗口.所以我得到 -

["731", "316", "167", "671", "717"]

这种方法会怎样?直接的方法是放入 for 循环并迭代.但我觉得一些内置的 python 字符串函数可以用更少的代码来做到这一点.知道任何这样的方法吗?

解决方案

itertools 示例 提供了可以做到这一点的 window 函数:

from itertools import islice定义窗口(seq,n=2):从可迭代对象的数据上返回一个滑动窗口(宽度为 n)"" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ..."it = iter(seq)结果 = 元组(islice(it, n))如果 len(result) == n:产出结果对于其中的元素:结果 = 结果 [1:] + (elem,)产出结果

示例用法:

<预><代码>>>>["".join(x) for x in window("7316717", 3)]['731'、'316'、'167'、'671'、'717']

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']

这篇关于Python在移动窗口中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆