生成列表中的分段随机单词列表

时间:2013-03-26 09:25:27

标签: python random

我从这里得到了这个:Generating random words

import random

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

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

applesomethinghellohellolalala

如何对随机单词进行分段,以便获得以下结果?

  

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

2 个答案:

答案 0 :(得分:1)

试试这个:

import random

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

答案 1 :(得分:0)

而不是使用

random.sample(words, 1)[0]
如同Eugeny提议的那样,我宁愿使用random.choice

print [random.choice(words) for i in range(10)]
相关问题