循环列表,就好像最后一个元素在第一个元素之前



如果列表中有n个元素,我希望从第一个元素开始,然后为整个列表切片接下来的x个元素,以便它将列表中的最后一个元素视为位于第一个元素之前。

的例子:

如果我想要5个元素的切片,我的列表是:

lst = ["a", "b", "c", "d", "e", "f"]

我想要每个切片的输出:

['b', 'c', 'd', 'e', 'f']
['c', 'd', 'e', 'f', 'a']
['d', 'e', 'f', 'a', 'b']
['e', 'f', 'a', 'b', 'c']
['f', 'a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']

这是我当前的代码:


lst = ["a", "b", "c", "d", "e", "f"]
i = 1
j = 6
while i <len(l):
print(l[i:j], end = " ")
i += 1
j += 1

我当前的输出是:

['b','c','d','e','f']
['c', 'd', 'e', 'f']
['d', 'e', 'f']
['e', 'f']
['f']

您可以这样做:

lst = ["a", "b", "c", "d", "e", "f"]
for i, _ in enumerate(lst):
print(lst[i+1:] + lst[:i])

在您的代码中,当列表索引超出范围时(在您增加j之后),它本质上什么也不做,与lst[i:]相同

你可以使用模

l = ["a", "b", "c", "d", "e", "f"]
i = 1
j = 6
n=len(l)
while i <=len(l):
k=i
for k in range (i,j):
print(l[k%n], end = " ")
print()
i += 1
j += 1

输出:

b c d e f 
c d e f a 
d e f a b 
e f a b c 
f a b c d 
a b c d e 

你可以让你的切片工作通过加倍列表(尝试在线!):

lst = ["a", "b", "c", "d", "e", "f"]
i = 1
j = 6
l = lst * 2
while i <= len(lst):
print(l[i:j])
i += 1
j += 1

另一种方法(尝试在线!):

lst = ["a", "b", "c", "d", "e", "f"]
for _ in lst:
x = lst.pop(0)
print(lst)
lst.append(x)

你可以直接" rotate"列表:

lst = ['a', 'b', 'c', 'd', 'e', 'f']
s = 5  # size of slices
n = 6  # number of slices
for _ in range(n):
lst.append(lst.pop(0))
print(lst[:s])

或者使用Deque,只是为了好玩:

from collections import deque
from itertools import islice
lst = ['a', 'b', 'c', 'd', 'e', 'f']
q = deque(lst)
s = 5  # size of slices
n = 6  # number of slices
for _ in range(n):
q.rotate(-1)
print(list(islice(q, 0, s)))