0

I currently have this in my Python script which is scheduled to run every 30s:

import random 
myList = ["12345", "123456", "1234567", "12345678"]
mySelection = random.choice(myList)

However, I'm looking for a solution that will select item from the list not randomly but in an order of the list items each time script runs (each 30s). For example:

  • my.py runs for the first time and mySelection = "12345"
  • my.py runs for the second time and mySelection = "123456"
  • my.py runs for the third time and mySelection = "1234567"
  • my.py runs for the fourth time and mySelection = "12345678"
  • my.py runs for the fifth time and mySelection = "12345" - this is when it starts over from the beginning of the list.
  • and so on...

Could someone help with this?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Baobab1988
  • 685
  • 13
  • 33

2 Answers2

2

One option would be to simply save the variable or index of the next wanted mySelection in a file and once you have read the value, you increment it by 1 and save the file again. This could be done with a simple text file or for example using the Pickle module if you want to be able to save more complex objects.

JakobVinkas
  • 1,003
  • 7
  • 23
0

How about this:

from itertools import cycle
cycled_list = cycle(myList)

# every time you call next(cycled_list)
# you get elements from it
next(cycled_list)  # '12345'
next(cycled_list)  # '123456'
next(cycled_list)  # '1234567'
next(cycled_list)  # '12345678'
next(cycled_list)  # '12345'  # cycling iteration
  • Thanks! However it prints this instead of the actual list value ` ` would you know how can i solve this? thx – Baobab1988 Jun 26 '20 at 11:39
  • @Baobab1988 if you print the `cycled_list `it would print that. However printing the `print(next(cycled_list))` returns actual result. – Nikita Alkhovik Jun 26 '20 at 13:22