Python范围从开始大于停止

时间:2016-06-28 11:57:50

标签: python loops indexing

我想统一提取向量的i索引t次。例如,如果我有一个向量x = [1,2,3,4,5,6,7]i = 3t = 5,我每次的索引必须是:

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 中执行此操作?

2 个答案:

答案 0 :(得分:3)

您可以在itertools.islice上使用itertools.cycle。从iterable中创建一个cycle对象,并使用窗口大小slice创建i对象:

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 :(得分: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]