像滑动窗口一样遍历列表

时间:2014-06-03 15:24:26

标签: python

如何在python中实现类似于滑动窗口方法的这种迭代。

Given s = [1, 2, 3, 4, 5, 6]

[1, 2, 3]
   [2, 3, 4]
      [3, 4, 5]    
         [4, 5, 6]
            [5, 6]
               [6]

1 个答案:

答案 0 :(得分:2)

l = [1, 2, 3, 4, 5, 6]    
for i in range(len(l)):
    print l[i : i+3]

输出

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]