从lis生成随机分词列表

2024-04-18 02:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我从这里得到:Generating random words

import random

words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala'] 

''.join(random.sample(words, 10))

applesomethinghellohellolalala

如何分割随机单词以便得到下面的结果?你知道吗

words = ['apple', 'something', 'hello', 'hello', 'lala']


Tags: sampleimportapplehellorandom单词somethingwords
2条回答

而不是使用

random.sample(words, 1)[0]

正如Eugeny所建议的,我宁愿使用random.choice

print [random.choice(words) for i in range(10)]

试试这个:

import random

words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print [random.sample(words, 1)[0] for i in range(10)]

相关问题 更多 >