我有一个如下所示的列表
list1 = [cont1,cont2,cont4,cont5]
如何在python中实现循环逻辑来选择列表的元素, 每次我尝试访问元素
答案 0 :(得分:5)
我建议使用itertools.cycle
。
使迭代器从iterable返回元素并保存a 每个的副本。当iterable耗尽时,返回from中的元素 保存副本。无限期地重复。
样本用法:
seq = [1,2,3,4]
round_robin = itertools.cycle(seq)
assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4
assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4
答案 1 :(得分:0)
seq = [1,2,3,4]
n = -1
def round_rob_seq():
global n
n = n + 1
return seq[n % len(seq)]
or
def round_rob_seq():
global n
n = n + 1
if n == len(seq):
n = 0
return seq[n]