I am trying to retrieve a random string from python list to build a word guess challenge. I deployed anaconda environment on Alibaba Cloud ECS Instance.
I often use the following method to retrieve a random string from the list.
Let's say
WordStack=['A','B','C','D']
print(WordStack[random.randint(len(WordStack))])
Is there any optimized way or build-in funtion to do that? Due to a large number of words, it takes some time to give the result.
Take a look at random.choice
which does exactly what you need. For your case, it would look like this:
WordStack = ['A','B','C','D']
random_str = random.choice(WordStack)
print(random_str) # -> whatever
Having said that, I wouldn't expect it to make such a big difference on the speed of the process. But If I find the time I will test it.
You could try random.randrange() instead of random.randint().
random.randrange():
Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn't actually build a range object.
From https://docs.python.org/3/library/random.html#random.randrange
I am not aware of any built-in function that does this.
So the equivalent statement would be:
WordStack[random.randrange(len(WordStack))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.