我有一个列表,我希望能够按顺序返回每个项目,当它到达最后一个项目 (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/