我正在尝试创建一个包含在列表中的一定数量的不同单词的字符串,但是我使用的代码只是随机使用一个单词,而不是每个打印的单词都使用不同的单词.
这是我的代码:
import random
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words) * 5
Run Code Online (Sandbox Code Playgroud)
示例输出将是:
hellohellohellohellohello
预期输出的示例将是:
appleyeahhellonopesomething
谁能告诉我我做错了什么?
random.choice(words) * 5
random.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
.
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)
归档时间: |
|
查看次数: |
5578 次 |
最近记录: |