生成随机单词

use*_*933 2 python random

我正在尝试创建一个包含在列表中的一定数量的不同单词的字符串,但是我使用的代码只是随机使用一个单词,而不是每个打印的单词都使用不同的单词.

这是我的代码:

import random

words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words) * 5
Run Code Online (Sandbox Code Playgroud)

示例输出将是:

hellohellohellohellohello

预期输出的示例将是:

appleyeahhellonopesomething

谁能告诉我我做错了什么?

jam*_*lak 7

random.choice(words) * 5random.choice只执行一次,然后将结果乘以5,从而导致重复相同的字符串.

>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
Run Code Online (Sandbox Code Playgroud)

  • `sample()`(如下所示)可能是更好的方法. (2认同)

Aka*_*all 5

如果您不希望重复原始列表中的单词,则可以使用sample.

import random as rn
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']

word = ''.join(rn.sample(words, 5))
Run Code Online (Sandbox Code Playgroud)

结果:

>>> word
'yeahhellosomethingapplenope'
Run Code Online (Sandbox Code Playgroud)