1

有没有办法像整数一样随机化一组字符串?

我举个例子:

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

有没有一种简单的方法可以使这成为可能?

4

2 回答 2

16

试试这个,这是惯用的解决方案:

import random
a = ['off', 'it', 'on', 'not']
random.choice(a)
=> 'on' # just an example, it's a random output

上面的代码使用了该choice()函数,请查看文档以获取更多详细信息。

于 2013-09-13T21:58:30.720 回答
3

像这样:

a = ["off","it","on","not"]
a[random.randint(0, len(a))]
于 2013-09-13T21:57:18.260 回答