在Python中随机连接字符串

mar*_*ams 0 python random join list range

我正在寻找列表中的单词以不同的组合连接在一起,但它只返回单个单词结果.我正在寻找像'whywho''whatwhywhen''howwhywhatwho'等字符串.

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

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

mar*_*dze 7

使用sample随机包中的函数.

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

for i in range(100):
    print ''.join(random.sample(words, random.randint(1,4)))
Run Code Online (Sandbox Code Playgroud)

编辑

如果你不关心要重复哪个元素,

for i in range(100):
    arr = random.sample(words, random.randint(1,4))
    # select a random element from arr and append to self     
    arr.append(random.choice(words))
    print ''.join(arr)
Run Code Online (Sandbox Code Playgroud)

如果您不希望重复此操作,如果已经重复,

    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)
Run Code Online (Sandbox Code Playgroud)

您可能还想使用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)
Run Code Online (Sandbox Code Playgroud)

检查为最后一个.