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
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With