gpt4 book ai didi

python - Python 中的循环迭代器

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:14 25 4
gpt4 key购买 nike

我正在解决一个编程问题,我需要从数组/列表中的任何给定位置开始并迭代直到我到达起始位置。我考虑过类似方法(出队)的循环缓冲区,但我不确定是否有迭代方法可以做到这一点。

给定:

[1,10,20]

所以当我在位置开始迭代时:1 我希望迭代输出为:

10, 20, 1

我目前的解决方案:

startPosition = 1
data = [1,10,20]
for i in range(0, 3):
pos = (startPosition+i)%3
print data[pos]

还有其他优雅的解决方案吗?还是一个容器这样做?

研究:

我从 itertools 遇到了 cycle 但这是一个无限循环。我将不得不使用下一个方法来获取并停止在正确的位置。 Circular list iterator in Python

最佳答案

正如您提到的,您可以使用恰好在标准库中的双端队列:

from collections import deque

startPosition = 1
data = [1,10,20]

d = deque(data)
d.rotate(-startPosition)

您必须否定 rotate 的方向,因为默认情况下它会向右旋转。

关于python - Python 中的循环迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com