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))))
Auf dieser Seite können Sie das Online-Video Select a random Item from a Python List - Python Recipes mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer TekMinded - Python Recipes 08 November 2020 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 4,058 Mal angesehen und es wurde von 82 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!