Skip to content Skip to sidebar Skip to footer

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

Solution 1:

If listOfItems can be shuffled, then

import randomrandom.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 randomfor item inrandom.sample(listOfItems, len(listOfItems))
    blahblah

Solution 2:

import random
random.shuffle(listOfItems)

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

Solution 3:

Well if performance isn't that important you could just shuffle your items, or if those have to stay in the same order create a list of all indizes and shuffle that (eg indizes = range(len(listOfItems)), random.shuffle(indizes))

Solution 4:

>>>lst = ['a', 'b', 'c', 'd']>>>nums = list(range(0, len(lst)))>>>import random>>>random.shuffle(nums)>>>for i in nums:...print lst[i]
c
a
b
d

Or if the list is really large you can use a bit of generator flavoring. :-)

Post a Comment for "Python - Run Through A Loop In Non Linear Fashion"