Python - Runs through a loop in a non-linear fashion

SO, I am looking for a way to iterate over a list of elements in loop mode, except that I want the loop to repeat “randomly”. that is, I don’t want the loop to go through 0,1,2,3, m + 1 ... n, I want him to select it in some random order and still run the loop for all the elements.

Here is my current loop code:

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

please let me know if this makes no sense;)

+4
source share
4 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

Change for Jochen Ritzel the best approach in commentary.
Otherwise it may be

import random
for item in random.sample(listOfItems, len(listOfItems))
    blahblah
+9
source
import random
random.shuffle(listOfItems)

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

, , , (, indizes = range (len (listOfItems)), .shuffle(indizes))

+1
>>> 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 long, you can use a little taste of the generator. :-)

0
source

All Articles