Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - run through a loop in non linear fashion

SO, I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. i.e. I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for all items.

Here is my current looping code:

for singleSelectedItem in listOfItems:
  item = singleSelectedItem.databaseitem
  logging.info(str(item))    

please let me know if this doesnt make sense ;)

like image 507
oberbaum Avatar asked Dec 22 '22 12:12

oberbaum


1 Answers

If listOfItems can be shuffled, then

import random
random.shuffle(listOfItems)
for singleSelectedItem in listOfItems:
    blahblah

otherwise

import random
randomRange = range(len(listOfItems))
random.shuffle(randomRange)
for i in randomRange:
    singleSelectedItem = listOfItems[i]
    blahblah

Edit for Jochen Ritzel's better approach in the comment.
The otherwise part can be

import random
for item in random.sample(listOfItems, len(listOfItems))
    blahblah
like image 183
clyfish Avatar answered Dec 24 '22 01:12

clyfish