Python程序在自定义索引处重复元素
给定一个列表,以下程序重复那些位于自定义索引处的元素,这些自定义索引作为单独的列表提供给它。
Input : test_list = [4, 6, 7, 3, 1, 9, 2, 19], idx_list = [3, 1, 6]
Output : [4, 6, 6, 7, 3, 3, 1, 9, 2, 2, 19]
Explanation : All required index elements repeated, Eg. 6 repeated as it is at index 1.
Input : test_list = [4, 6, 7, 3, 1, 9, 2, 19], idx_list = [1, 6]
Output : [4, 6, 6, 7, 3, 1, 9, 2, 2, 19]
Explanation : All required index elements repeated, 6 repeated as it is at index 1.
方法:使用循环和扩展()
在这种情况下,我们执行重复每个元素的任务,以防它是使用 extend() 重复所需的索引,并且循环用于迭代每个索引。 enumerate() 用于获取所有索引以及元素。
程序:
Python3
# initializing list
test_list = [4, 6, 7, 3, 1, 9, 2, 19]
# printing original list
print("The original list is : " + str(test_list))
# initializing index list
idx_list = [3, 1, 4, 6]
res = []
for idx, ele in enumerate(test_list):
if idx in idx_list:
# incase of repetition
res.extend([ele, ele])
else :
res.append(ele)
# printing result
print("The Custom elements repetition : " + str(res))
输出:
The original list is : [4, 6, 7, 3, 1, 9, 2, 19]
The Custom elements repetition : [4, 6, 6, 7, 3, 3, 1, 1, 9, 2, 2, 19]