[英]How can I infinitely iterate through a list while specifying the starting index?
[英]How to iterate through list infinitely with +1 offset each loop
我想從 0 到結尾無限迭代列表,但是在下一個循環中,我想從 1 開始到結尾加上 0,下一個循環將從 2 開始到結尾加上 0、1,直到最后一個項目,它將從 0 重新開始並走到最后。
這是我的代碼:
a = [ 0, 1, 2 ]
offset = 0
rotate = 0
while True:
print(a[rotate])
offset += 1
rotate += 1
if offset >= len(a):
offset = 0
rotate += 1
if rotate >= len(a):
rotate = 0
這是我到目前為止提出的解決方案。 它遠非完美。
我想要的結果是:
0, 1, 2 # first iteration
1, 2, 0 # second iteration
2, 0, 1 # third iteration
0, 1, 2 # fourth iteration
等等。
您可以使用具有內置且高效的旋轉功能 (~O(1)) 的deque
:
>>> d = deque([0,1,2])
>>> for _ in range(10):
... print(*d)
... d.rotate(-1) # negative -> rotate to the left
...
0 1 2
1 2 0
2 0 1
0 1 2
1 2 0
2 0 1
0 1 2
1 2 0
2 0 1
0 1 2
嘗試這個:
a = [0, 1, 2]
while True:
print(*a, sep=', ')
a.append(a[0])
a.pop(0)
輸出:
0, 1, 2
1, 2, 0
2, 0, 1
0, 1, 2
1, 2, 0
2, 0, 1
...
或者, pop
返回移除的元素,所以可以簡化
a = [0, 1, 2]
while True:
print(*a, sep=', ')
a.append(a.pop(0))
[感謝 ShadowRanger 和 Tomerikoo 的改進建議。]
您可以使用列表切片創建具有偏移量的列表,然后使用itertools.cycle()
無限重復它們。 這僅計算一次所有旋轉,然后循環遍歷所有旋轉:
from itertools import cycle, islice
lst = [0, 1, 2]
items = [lst[i:] + lst[:i] for i in range(len(lst))]
iterator = cycle(items)
for item in islice(iterator, 10):
print(item)
一旦您通過了預計算,上述方法很快,但您可能(取決於您的用例)更喜歡一種沒有前期時間/空間成本的方法。 在這種情況下,您可以改用生成器:
from itertools import cycle, islice
def rotate(lst):
for offset in cycle(range(len(lst))):
yield lst[offset:] + lst[:offset]
lst = [0, 1, 2]
for item in islice(rotate(lst), 10):
print(item)
這兩個輸出:
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 2]
這些代碼片段已根據wjandrea的建議進行了改進。
在這里,您還有另一種使用指針的選擇:
a = [ 0, 1, 2 ]
i = 0
l = len(a)
while True:
out = []
for j in range(i, i+l):
out.append(a[j%l])
print(out)
i=(i+1)%l
輸出:
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
[0, 1, 2]
[1, 2, 0]
[2, 0, 1]
另一種選擇,使用列表切片:
cycles = [a[i:]+a[:i] for i, _ in enumerate(a)]
while True:
for c in cycles: print(c)
或者,如果您不想預先計算cycles
的O(n^2)
空間,您可以繼續重新制作周期:
from itertools import count
n = len(a)
for i in count():
j = i%n
print(a[j:]+a[:j])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.