Python – 自定义元素重复
给定元素列表和所需的出现列表,执行元素的重复。
Input : test_list1 = [“Gfg”, “Best”], test_list2 = [4, 5]
Output : [‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Best’, ‘Best’, ‘Best’, ‘Best’, ‘Best’]
Explanation : Elements repeated by their occurrence number.
Input : test_list1 = [“Gfg”], test_list2 = [5]
Output : [‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]
Explanation : Elements repeated by their occurrence number.
方法 #1:使用循环 + 扩展()
上述功能的组合提供了可以执行此任务的方式之一。在此,我们使用循环进行迭代,并使用extend() 对元素进行重复扩展。
Python3
# Python3 code to demonstrate working of
# Custom elements repetition
# Using loop + extend()
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 3, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using loop to perform iteration
res = []
for idx in range(0, len(test_list1)):
# using extend to perform element repetition
res.extend([test_list1[idx]] * test_list2[idx])
# printing result
print("The repeated list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Custom elements repetition
# Using loop + zip()
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 3, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() to intervene elements and occurrence
res = []
for ele, occ in zip(test_list1, test_list2):
res.extend([ele] * occ)
# printing result
print("The repeated list : " + str(res))
输出
The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : [4, 3, 5]
The repeated list : ['Gfg', 'Gfg', 'Gfg', 'Gfg', 'is', 'is', 'is', 'Best', 'Best', 'Best', 'Best', 'Best']
方法 #2:使用循环 + zip()
这是可以执行此任务的另一种方式。在此,我们使用 zip() 将元素与其重复出现匹配并执行所需的重复任务。
Python3
# Python3 code to demonstrate working of
# Custom elements repetition
# Using loop + zip()
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 3, 5]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() to intervene elements and occurrence
res = []
for ele, occ in zip(test_list1, test_list2):
res.extend([ele] * occ)
# printing result
print("The repeated list : " + str(res))
输出
The original list 1 : ['Gfg', 'is', 'Best']
The original list 2 : [4, 3, 5]
The repeated list : ['Gfg', 'Gfg', 'Gfg', 'Gfg', 'is', 'is', 'is', 'Best', 'Best', 'Best', 'Best', 'Best']