Mélanger aléatoirement une liste sous python
Avec python on peut facilement mélanger aléatoirement les éléments d'une liste en utilisant shuffle. Exemple:
>>> import random>>> L = ['a','b','c','d','e','f']>>> random.shuffle(L)>>> L['b', 'c', 'a', 'd', 'f', 'e']>>>
Mélanger aléatoirement avec un paramètre pour obtenir toujours le même résultat:
Il est aussi possible de mélanger aléatoirement avec un paramètre (lambda) pour obtenir toujours le même résultat (voir python shuffling with a parameter to get the same result):
>>> import random>>> r = random.random()>>> r0.4309619702601998>>> x = [1, 2, 3, 4, 5, 6]>>> random.shuffle(x, lambda: r)>>> x[5, 1, 4, 2, 6, 3]>>> random.shuffle(x, lambda: r)>>> x[6, 5, 2, 1, 3, 4]>>> x = [1, 2, 3, 4, 5, 6]>>> random.shuffle(x, lambda: r)>>> x[5, 1, 4, 2, 6, 3]
Recherches associées
| Liens | Site |
|---|---|
| 9.6. random — Generate pseudo-random numbers | Python Doc |
| Shuffling a list of objects in python | stackoverflow |
| python shuffling with a parameter to get the same result | stackoverflow |
