python - Comment puis-je sélectionner au hasard un article dans une liste

Mots clés : pythonlistrandompython

meilleur 5 Réponses python - Comment puis-je sélectionner au hasard un article dans une liste

vote vote

93

import random  foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) 
import secrets  foo = ['battery', 'correct', 'horse', 'staple'] print(secrets.choice(foo)) 
import random  secure_random = random.SystemRandom() print(secure_random.choice(foo)) 
vote vote

88

import random group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here. num_to_select = 2                           # set the number to select here. list_of_random_items = random.sample(group_of_items, num_to_select) first_random_item = list_of_random_items[0] second_random_item = list_of_random_items[1]  
import secrets                              # imports secure module. secure_random = secrets.SystemRandom()      # creates a secure random object. group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here. num_to_select = 2                           # set the number to select here. list_of_random_items = secure_random.sample(group_of_items, num_to_select) first_random_item = list_of_random_items[0] second_random_item = list_of_random_items[1] 
import random first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2) 
vote vote

70

from random import randrange random_index = randrange(len(foo)) print(foo[random_index]) 
vote vote

68

import secrets foo = ['a', 'b', 'c', 'd', 'e'] print(secrets.choice(foo)) 
print(secrets.randbelow(len(foo))) 
vote vote

55

s=set(range(1,6)) import random  while len(s)>0:   s.remove(random.choice(list(s)))   print(s) 
>>>  set([1, 3, 4, 5]) set([3, 4, 5]) set([3, 4]) set([4]) set([]) >>>  set([1, 2, 3, 5]) set([2, 3, 5]) set([2, 3]) set([2]) set([])  >>>  set([1, 2, 3, 5]) set([1, 2, 3]) set([1, 2]) set([1]) set([]) 

Questions similaires