In Python 3.x, I need to choose at random an integer between 0 and the length of a given list, inclusive. In other words, given
mylist = [0, 5, 6, 8, -10]
I want to return a number between 0 and 5, inclusive. What's the most Pythonic way to do it? I tried
import numpy as np
my_list = [0, 5, 6, 8, -10]
def choose_at_random(a_list):
choice = np.random.randint(0, len(a_list) + 1)
return choice
This works, but is this the Pythonic way to do it? The need to +1
the list length seems a bit error-prone (I mean, it's easy to forget to do it).
Aucun commentaire:
Enregistrer un commentaire