简体   繁体   English

除了在索引中使用random.randint()之外,如何从python列表中选择随机字符串?

[英]How do i choose random string from python list other than using random.randint() in index?

I am trying to retrieve a random string from python list to build a word guess challenge. 我正在尝试从python列表中检索随机字符串以构建单词猜测挑战。 I deployed anaconda environment on Alibaba Cloud ECS Instance. 我在阿里云ECS实例上部署了anaconda环境。

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. 看看random.choice正是您所需要的。 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()代替random.randint()。

random.randrange(): 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. 这等效于choice(range(start(开始,停止,步进)),但实际上并不构建range对象。

From https://docs.python.org/3/library/random.html#random.randrange 来自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))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM