Python – 随机插入元素 K 次
给定 2 个列表,将列表 2 中的随机元素插入列表 1,在随机位置 K 次。
Input : test_list = [5, 7, 4, 2, 8, 1], add_list = [“Gfg”, “Best”, “CS”], K = 2
Output : [5, 7, 4, 2, 8, 1, ‘Best’, ‘Gfg’]
Explanation : Random elements from List 2 are added 2 times.
Input : test_list = [5, 7, 4, 2, 8, 1], add_list = [“Gfg”, “Best”, “CS”], K = 1
Output : [5, 7, 4, 2, 8, 1, ‘Gfg’]
Explanation : Random elements from List 2 are added 1 times.
方法:使用 randint() + 列表切片 + 循环 + 选择()
在此,choice() 用于从列表 2 中获取随机元素以插入到列表 1 中,而 randint() 用于获取需要插入的索引。然后列表切片用于根据更新的顺序重新制作列表。
Python3
# Python3 code to demonstrate working of
# Random insertion of elements K times
# Using randint() + list slicing + loop + choice()
import random
# initializing list
test_list = [5, 7, 4, 2, 8, 1]
# printing original list
print("The original list : " + str(test_list))
# initializing add list
add_list = ["Gfg", "Best", "CS"]
# initializing K
K = 3
for idx in range(K):
# choosing index to enter element
index = random.randint(0, len(test_list))
# reforming list and getting random element to add
test_list = test_list[:index] + [random.choice(add_list)] + test_list[index:]
# printing result
print("The created List : " + str(test_list))
输出
The original list : [5, 7, 4, 2, 8, 1]
The created List : [5, 7, 4, 2, 'Best', 8, 1, 'Best', 'Gfg']