生成随机词 [英] Generating random words
问题描述
我正在尝试创建一个字符串,其中包含我包含在列表中的一组不同单词,但是我使用的代码仅随机使用一个单词,而不是每个打印的单词都使用不同的单词.
这是我的代码:
随机导入words = ['你好', 'apple', 'something', 'yeah', 'nope', 'lalala']打印 random.choice(words) * 5
示例输出为:
hellohellohellohellohello
预期输出示例如下:
appleyeahhellonopesomething
谁能告诉我我做错了什么?
random.choice(words) * 5
只执行一次 random.choice
然后将结果相乘5,导致重复相同的字符串.
I'm trying to create a string that has a set amount of different words I include in a list, however the code I use only uses one word at random, not a different word for every word printed.
This is my code:
import random
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words) * 5
An example output would be:
hellohellohellohellohello
An example expected output would be:
appleyeahhellonopesomething
Can anyone tell me what I'm doing wrong?
random.choice(words) * 5
executes random.choice
only once and then multiplies the result by five, causing the same string to be repeated.
>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolalala
这篇关于生成随机词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!