在Python中随机连接字符串

2024-10-03 09:10:01 发布

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

我在寻找列表中的单词以不同的组合组合在一起,但它只返回单个单词的结果。我在找“whywho”“whatwhen”“howhwhwhwhwhwho”等字符串

import random, sys
words = ['why', 'who', 'what', 'why', 'when', 'how']

for i in range(100):
    print ''.join(random.choice(words[:randint(1, 4)]))

Tags: 字符串import列表sysrandom单词whathow
3条回答

使用随机包中的sample函数。在

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)

最后一个检查this。在

试试这个。只需找到一个随机索引,并用一个随机列表join。要计算单词的生成次数,请使用collections命名空间中的Counter对象。在

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})

你很接近答案!在

random.choice从输入序列返回一个随机元素。您要做的是从words列表中生成一个随机大小的片段,从中选择一个元素。在

以下是您想要的:

''.join(random.choices(words, k=random.randint(1, 4)))

random.choices从输入序列返回一个k大小的随机元素列表。这些元素是通过替换选择的,这意味着您可能有来自words的多个元素。在

相关问题 更多 >