python - 遍历列表并从头开始重新启动

我有一个列表,我希望能够按顺序返回每个项目,当它到达最后一个项目 (a7) 时,继续从头开始运行。一个额外的复杂性是脚本不会连续运行(它是手动停止和启动的)所以它需要以某种方式存储以前调用的项目,以便在下次运行脚本时它可以工作。

这是列表的摘录:

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']

脚本的基本逻辑是:

if var_one == var_two:
    [return next item from part_list]

所以,第一次运行应该返回 a1,第二次运行应该返回 a2,第三次返回 a3,等等。

最佳答案

使用itertools.cycle :

from itertools import cycle
part_cycle = cycle(['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7'])

# below code is part of a function
if var_one == var_two:
    return next(part_cycle)

将状态保存在解释器之外的替代方法

n = 4 ## counter to save (could use a file, database, pickle, etc.)
      ## ensure that the type is int

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']

# below code is part of a function
if var_one == var_two:
    n += 1
    return part_list[n%len(part_list)]
完整演示
# read the saved counter, or initialize
try:
    with open('state.txt', 'r') as f:
        idx = int(f.read().strip())
        print(idx)
except FileNotFoundError:
    idx = -1

part_list = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']    

# this is the part where the computation is done
# replace it with your function
# the critical steps are:
#   1- to increase the counter
#   2- to slice using the modulo (part_list[idx%len(part_list)])
for i in range(10):
    idx += 1
    print(part_list[idx%len(part_list)])

# save the counter
with open('state.txt', 'w') as f:
    f.write(f'{idx}')

https://stackoverflow.com/questions/69991335/

相关文章:

asp.net-core - 安装 .NET 6 后无法创建 EF 迁移

node.js - 使用 Fastify : "@nestjs/platform-express"

c# - 为什么不推荐使用堆来排序LinkedList?

php - undefined variable : data , $data 未定义。拉维尔 8

r - 如何对该数据集进行排序以创建合适的数据框

reactjs - 如何将参数传递给从自定义 Hook 转换的函数?

python - 算法题: Finding the cheapest flight

python - AttributeError : module 'cv2.cv2' has no

r - R中多列的值计数

bash - 组合两个 grep 命令来处理来自文件的输入,或者 grep 行以一个特定的子字符串开