python - 将字符随机插入字符串数组最少次数
问题描述
给定一个字符串数组,我想在一次遍历数组时随机插入字符至少一定次数
# 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)
推荐阅读
- javascript - Outlook 插件上传 FileReference 作为附件
- flutter - Flutter 2.0 - 自动完成小部件从右侧退出屏幕
- javascript - 我如何合并 2 个数组,如果重复,需要将它们添加在一起
- c - 如何画一条斜线
- nodes - 活动工作节点如何与最小工作节点和最大工作节点一起工作
- javascript - 切换到 Typescript 后找不到 App.js
- javascript - JavaScript 算法通过删除最多一个字符来检查回文 - 这种递归方法的时间复杂度
- reactjs - 情感 - 导入项目并出现错误 TypeError: Object(...) is not a function
- pine-script - 不断收到此消息:不能使用可变变量作为安全函数的参数
- python - 张量流错误:不支持将字符串转换为浮点数