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)?
You can use to list: random.shuffle() random.shuffle()
random.shuffle()
import random r = list(range(1000)) random.shuffle(r) for i in r: # do something with i
, , for , "", Python., i , :
for
i
lst = [1970, 1991, 2012] random.shuffle(lst) for x in lst: print x
: random.shuffle() ( :
, len (x) x , ; , .
. " ":
def randomly(seq): shuffled = list(seq) random.shuffle(shuffled) return iter(shuffled)
for i in randomly(range(1000)): #.. we're good to go ..
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.
random.shuffle
. , deck[i] = deck.pop() , .
deck[i] = deck.pop()
numpy random.permutation() .
numpy
random.permutation()
from numpy.random import permutation for i in permutation(1000): # do something with i
Use the random.shuffle method:
itrange = list(range(100)) random.shuffle(itrange) for i in itrange: print i
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