2016-06-28 45 views
1

我想提取一個向量的i指數一致t次。舉例來說,如果我有一個載體x = [1,2,3,4,5,6,7]i = 3t = 5,我每次在指數必須是:Python的範圍與開始大於停止

t = 1; [1,2,3] 

t = 2; [4,5,6] 

t = 3; [7,1,2] 

t = 4; [3,4,5] 

t = 5; [6,7,1] 

是否有可能與range()做到在Python的

+0

itertools模塊應該很有用,一個例子:http://stackoverflow.com/questions/2167868/getting-next-element-while-cycling-through-a-list – Mel

回答

3

您可以在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]] 
1

試試這個:

x = [1,2,3,4,5,6,7] 
xc = len(x) 
i = 3 

for t in range(5): 
    y = [x[(i*t + j) % xc] for j in range(i)] 
    print(y) 

這將產生:

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