import random
words = ['why', 'who', 'what', 'why', 'when', 'how']
for i in range(100):
print ''.join(random.sample(words, random.randint(1,4)))
编辑
如果你不在乎要重复哪个元素
^{pr2}$
如果您不希望在重复的情况下重复此操作
arr = random.sample(words, random.randint(1,4))
# first check if array contains repetetive elements or not
# if contains, go and join the list, otherwise select a random element
# from array and add to that array again
if not [el for el in arr if arr.count(l) > 1]:
arr.append(random.choice(words))
print ''.join(arr)
您可能还想使用为列表定义的insert方法,它只需将元素插入到列表中所需的索引中。在
arr = random.sample(words, random.randint(1,4))
if not [el for el in arr if arr.count(el) > 1]:
r = random.choice(arr)
index_of_r = arr.index(r)
arr.insert(index_of_r, r)
print ''.join(arr)
import random as rand
import sys
from collections import Counter
words = ['why', 'who', 'what', 'why', 'when', 'how']
list = []
for i in range(100):
# print(words[rand.randint(1, 4)].join(words[:rand.randint(1, 4)]))
# print(rand.sample(words, rand.randint(1, 4))) Prints out a 'list' of current combination
list += rand.sample(words, rand.randint(1, 4))
c = Counter(list)
print(c) # Counter({'why': 93, 'who': 48, 'what': 46, 'how': 46, 'when': 35})
使用随机包中的
sample
函数。在编辑
如果你不在乎要重复哪个元素
^{pr2}$如果您不希望在重复的情况下重复此操作
您可能还想使用为列表定义的
insert
方法,它只需将元素插入到列表中所需的索引中。在最后一个检查this。在
试试这个。只需找到一个随机索引,并用一个随机列表
join
。要计算单词的生成次数,请使用collections
命名空间中的Counter
对象。在你很接近答案!在
random.choice
从输入序列返回一个随机元素。您要做的是从words
列表中生成一个随机大小的片段,从中选择一个元素。在以下是您想要的:
random.choices
从输入序列返回一个k
大小的随机元素列表。这些元素是通过替换选择的,这意味着您可能有来自words
的多个元素。在相关问题 更多 >
编程相关推荐