Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round robin to select elements of list

Tags:

python-2.7

I have a list like below

list1 = [cont1,cont2,cont4,cont5]

how do i implement round robin logic in python to select elements of a list, each time i try to access element

like image 539
user3625349 Avatar asked Jul 07 '16 16:07

user3625349


2 Answers

I'd suggest using itertools.cycle.

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

Sample usage:

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
like image 167
Łukasz Rogalski Avatar answered Oct 18 '22 14:10

Łukasz Rogalski


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]
like image 45
Alex Dowie Avatar answered Oct 18 '22 14:10

Alex Dowie