Comment sélectionner aléatoirement les éléments d'une liste ou d'un dictionnaire en python 2 ?


Pour sélectionner aléatoirement des éléments d'une liste sous python on peut utiliser la fonction random. choice():

>>> import random
>>> l = [i for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.choice(l)
1
>>> random.choice(l)
6

Marche aussi avec un dictionnaire:

>>> import random
>>> d = {'a':1,'b':2,'c':3,'d':4,'e':5
>>> random.choice(d.keys())
'c'
>>> random.choice(d.keys())
'b'

Si on veut sélectionner aléatoirement des éléments (créer un échantillon) sans remise on peut utiliser la fonction random.sample():

>>> import random
>>> l = [i for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.sample(l, 2)
[3, 5]
>>> random.sample(l, 2)
[5, 0]
>>> random.sample(l, 3)
[4, 8, 9]

avec un dictionnaire

>>> import random
>>> l = [i for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.sample(d.keys(), 3)
['b', 'c', 'a']
>>> random.sample(d.keys(), 2)
['b', 'd']
>>> random.sample(d.keys(), 2)
['b', 'e']

Références