将字符随机插入字符串数组最少次数

Insert characters randomly into string array a minimum amount of times

给定一个字符串数组,我想在数组 运行 中随机插入字符至少一定次数

# Very large array of strings in reality
text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
characters = ['♥', '♫']
# Guaranteed 2 times for example:
result = ['some', '♫', 'list', 'of', '♥', 'strings', 'really', '♥', 'long', 'one', 'at', '♫', 'that']
from random import randrange

text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
characters = ['♥', '♫']
no_of_reps = 2

def insert_to_random_index(array, characters, no_of_reps):
    for i in range(no_of_reps):
        for character in characters:        
            random_index = randrange(len(array))
            array = array[:random_index] +[character] + array[random_index:]
    return array

new_text = insert_to_random_index(text, characters, no_of_reps)
print(new_text)
import random

text = ['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
characters = ['♥', '♫']

print(text)
for i in range(0, random.randint(2, 10)):
    idx = random.randint(0, len(text))
    text = text[:idx] + [random.choice(characters)] + text[idx:]

print(text)

测试输出:

['some', 'list', 'of', 'strings', 'really', 'long', 'one', 'at', 'that']
['some', 'list', 'of', 'strings', '♫', 'really', 'long', 'one', '♫', 'at', 'that', '♫']

只需检查一下,如果您有任何疑问,请随时提问:

  import random

lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'


print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)