首页 > 解决方案 > 将字符随机插入字符串数组最少次数

问题描述

给定一个字符串数组,我想在一次遍历数组时随机插入字符至少一定次数

# 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']

标签: pythonarrayspython-3.xstringcharacter

解决方案


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)

推荐阅读