Random Iteration in Python

If you want to iterate over a list of numbers sequentially, you will write:

for i in range(1000):
  # do something with i

But what if you want to randomly iterate over a list of numbers from a range (0..999)? There is a need (at each iteration) to arbitrarily select a number that was not selected in any previous iteration, and it is necessary to sort out all numbers from the range (0..999).

Do you know how to do this (smart)?

+21
source share
6 answers

You can use to list: random.shuffle() random.shuffle()

import random

r = list(range(1000))
random.shuffle(r)
for i in r:
  # do something with i

, , for , "", Python.
, i , :

lst = [1970, 1991, 2012]
random.shuffle(lst)
for x in lst:
  print x

: random.shuffle() ( :

, len (x) x , ; , .

+25

. " ":

def randomly(seq):
    shuffled = list(seq)
    random.shuffle(shuffled)
    return iter(shuffled)

for i in randomly(range(1000)):
    #.. we're good to go ..
+16

Python -.

import random

def shuffled(sequence):
    deck = list(sequence)
    while len(deck):
        i = random.randint(0, len(deck) - 1) # choose random card
        card = deck[i]                       # take the card
        deck[i] = deck[-1]                   # put top card in its place
        deck.pop()                           # remove top card
        yield card

, . , , , , , random.shuffle.

. , deck[i] = deck.pop() , .

+6

numpy random.permutation() .

from numpy.random import permutation

for i in permutation(1000):
    # do something with i
+5

Use the random.shuffle method:

itrange = list(range(100))
random.shuffle(itrange)
for i in itrange:
    print i
+3
source

Here's a different approach to iterating a list in random order. This does not change the original list unlike solutions using shuffle ()

lst=['a','b','c','d','e','f']
for value in sorted(lst,key=lambda _: random.random()):
    print value

or:

for value in random.sample(lst,len(lst)):
    print value
0
source

All Articles