用于环状条件的Pythonic复合材料

时间:2017-01-17 04:18:47

标签: python

在C ++ / C中,我可以编写以下内容:

string s;
int window_len = 3;
for (int i = 0, j = window_len; j <= s.length(); i += window_len, j += window_len) {
  //do things with s.Slice(i, j)
}

是否有一种表达上述复合物的pythonic方法?

3 个答案:

答案 0 :(得分:2)

使用地板将字符串的长度除以&#34; group&#34; -size这一事实的一种方法将截断剩余的字符:

>>> string = 'abcdefghijklm'
>>> size=2

>>> [string[i*size:(i+1)*size] for i in range(len(string) // size)]
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

或者在for循环中:

for i in range(len(string) // size):
    substr = string[i*size:(i+1)*size]
    # do stuff with substr

答案 1 :(得分:1)

我认为这会以类似的方式获得概念,并且不需要额外的数学运算:

strides = range(0, len(s)+1, window_len)
for i, j in zip(strides, strides[1:]):
    # do something with s[i:j]

答案 2 :(得分:0)

为什么,当然:

s = "Hello, world!"
[s[i:i + window_len] for i in range(0, len(s)-window_len+1, window_len)]
# ['Hel', 'lo,', ' wo', 'rld']