我想统一提取向量的i
索引t
次。例如,如果我有一个向量x = [1,2,3,4,5,6,7]
,i = 3
和t = 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 中执行此操作?
答案 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]