您可以在itertools.cycle
使用itertools.islice
。使用您的窗口大小i
從迭代做出cycle
對象,slice
對象:
from itertools import cycle
from itertools import islice
l = [1,2,3,4,5,6,7]
t = 5; i = 3
c = cycle(l)
r = [list(islice(c, i)) for _ in range(t)] # range appears here
# [[1, 2, 3], [4, 5, 6], [7, 1, 2], [3, 4, 5], [6, 7, 1]]
您可以將此用於i
不同非負值,即使i
比列表的長度時, :
i = 10
r = [list(islice(c, i)) for _ in range(t)]
print(r)
# [[1, 2, 3, 4, 5, 6, 7, 1, 2, 3], [4, 5, 6, 7, 1, 2, 3, 4, 5, 6], [7, 1, 2, 3, 4, 5, 6, 7, 1, 2], [3, 4, 5, 6, 7, 1, 2, 3, 4, 5], [6, 7, 1, 2, 3, 4, 5, 6, 7, 1]]
itertools模塊應該很有用,一個例子:http://stackoverflow.com/questions/2167868/getting-next-element-while-cycling-through-a-list – Mel