要将元素添加到数组的随机位置,可以使用random模块中的randrange()函数来生成一个随机的索引位置,然后使用insert()方法将元素插入到数组的该位置。

下面是一个示例代码:

import random

def insert_random(arr, element):
    index = random.randrange(len(arr) + 1)  # 生成一个随机的索引位置
    arr.insert(index, element)  # 将元素插入到数组的随机位置

# 测试代码
my_array = [1, 2, 3, 4, 5]
insert_random(my_array, 6)
print(my_array)

运行结果可能是:

[1, 2, 3, 4, 6, 5]

以上代码将元素6添加到了数组my_array的随机位置。

python将数组将元素添加到随机的位置

原文地址: https://www.cveoy.top/t/topic/jclT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录