循环选择列表的元素

时间:2016-07-07 16:53:26

标签: python-2.7

我有一个如下所示的列表

list1 = [cont1,cont2,cont4,cont5]

如何在python中实现循环逻辑来选择列表的元素, 每次我尝试访问元素

2 个答案:

答案 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]