This video provides a quick tutorial on how to select a random item from a Python list using the random.choice method.
SUBSCRIBE TO OUR YOUTUBE CHANNEL
/ @tekminded
#python #recipes #dataanalytics #datascience #pandas #dataframe #random
Imagine that you want to build a magic ball functionality in a travel app where cities are picked at random from a pre-defined list of cities. In this video we review how to do that using the python random library and the choices() methods.
The process is quite simple. you just need to import the random library and then provide the list as argument to return one random items from the list. See code below:
import random
cities_to_visit=['Miami','New York','Paris','Bogota', 'Madrid']
print(random.randrange(cities_to_visit))
The implementation above assumes that every time you run the code all cities are presented as possible choices, which formally is the case of random selection with replacement.
It is also possible to implement it as a random selection without replacement. In this case we can use the python pop() method along with the random.randrange() method as noted in the code below.
import random
cities_to_visit=['Miami','New York','Paris','Bogota', 'Madrid']
while len(cities_to_visit)!=0:
print(cities_to_visit.pop(random.randrange(len(cities_to_visit))))
In questa pagina del sito puoi guardare il video online Select a random Item from a Python List - Python Recipes della durata di ore minuti seconda in buona qualità , che l'utente ha caricato TekMinded - Python Recipes 08 novembre 2020, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 4,058 volte e gli è piaciuto 82 spettatori. Buona visione!