Python – 列表元素的增量和循环重复
有时,在使用Python列表时,我们可能会遇到需要重复元素 K 次的问题。但是我们可以在这方面有变化,并且必须以循环和增量的方式重复元素。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + enumerate()
这是可以执行此任务的蛮力方式。在此,我们迭代元素并使用 mod运算符和乘法逻辑执行所需的重复次数。
Python3
# Python3 code to demonstrate
# Incremental and Cyclic Repetition of List Elements
# using loop + enumerate()
# Initializing list
test_list = ['g', 'f', 'g', 'C', 'S']
# printing original list
print("The original list is : " + str(test_list))
# Initializing range
i, j = 2, 4
# Incremental and Cyclic Repetition of List Elements
# using loop + enumerate()
res = []
temp = list(range(i, j + 1))
for idx, ele in enumerate(test_list):
res.append(ele * temp[idx % len(temp)])
# printing result
print ("Repetition List is : " + str(res))
Python3
# Python3 code to demonstrate
# Incremental and Cyclic Repetition of List Elements
# using cycle() + loop + zip()
from itertools import cycle
# Initializing list
test_list = ['g', 'f', 'g', 'C', 'S']
# printing original list
print("The original list is : " + str(test_list))
# Initializing range
i, j = 2, 4
# Incremental and Cyclic Repetition of List Elements
# using cycle() + loop + zip()
res = []
for k, l in zip(cycle(range(i, j + 1)), test_list):
res.append(k * l)
# printing result
print ("Repetition List is : " + str(res))
输出 :
The original list is : ['g', 'f', 'g', 'C', 'S']
Repetition List is : ['gg', 'fff', 'gggg', 'CC', 'SSS']
方法#2:使用循环()+循环+ zip()
这些任务的组合也可用于执行此任务。在此,我们使用循环和循环进行迭代,使用循环()执行重复。
Python3
# Python3 code to demonstrate
# Incremental and Cyclic Repetition of List Elements
# using cycle() + loop + zip()
from itertools import cycle
# Initializing list
test_list = ['g', 'f', 'g', 'C', 'S']
# printing original list
print("The original list is : " + str(test_list))
# Initializing range
i, j = 2, 4
# Incremental and Cyclic Repetition of List Elements
# using cycle() + loop + zip()
res = []
for k, l in zip(cycle(range(i, j + 1)), test_list):
res.append(k * l)
# printing result
print ("Repetition List is : " + str(res))
输出 :
The original list is : ['g', 'f', 'g', 'C', 'S']
Repetition List is : ['gg', 'fff', 'gggg', 'CC', 'SSS']