有没有办法随机化一组字符串,就像整数一样?
我举一个例子:
import random
random.randint(1, 30) #will produce random number between 1 and 30
对于一个字符串,我想从一个变量中随机化单词:
a="off","it","on","not"
random.randstr(a) #I understand that this isnt a real code and will produce and error
有没有一种简单的方法可以实现这一目标?
答案 0 :(得分:16)
试试这个,这是惯用的解决方案:
import random
a = ['off', 'it', 'on', 'not']
random.choice(a)
=> 'on' # just an example, it's a random output
上面的代码使用了choice()
函数,请查看documentation以获取更多详细信息。
答案 1 :(得分:3)
像这样:
a = ["off","it","on","not"]
a[random.randint(0, len(a))]