Python – 将每个连续的重复项加倍
有时,在处理数据时,我们可能会遇到一个问题,即我们需要在每次连续出现重复项时执行双重元素。这是一个非常具体的问题,但解决这个问题可以证明是非常方便的。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是执行此任务的蛮力方式。在此,我们迭代每个元素,当我们发现重复时,我们将其存储在字典中并随后执行其双精度。
# Python3 code to demonstrate
# Double each consecutive duplicate
# using loop
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
# printing original list
print("The original list is : " + str(test_list))
# Double each consecutive duplicate
# using loop
temp = {}
res = []
for ele in test_list:
temp[ele] = temp1 = temp.get(ele, 0) + ele
res.append(temp1)
# printing result
print ("The list after manipulation is : " + str(res))
输出 :
The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]
方法 #2:使用defaultdict()
+ 循环
此方法以与上述类似的方式执行此任务。唯一的区别是使用 defaultdict() 减少了一个步骤,因为它预先初始化了列表。
# Python3 code to demonstrate
# Double each consecutive duplicate
# using loop + defaultdict()
from collections import defaultdict
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
# printing original list
print("The original list is : " + str(test_list))
# Double each consecutive duplicate
# using loop + defaultdict()
temp = defaultdict(int)
res = []
for ele in test_list:
temp[ele] += ele
res.append(temp[ele])
# printing result
print ("The list after manipulation is : " + str(res))
输出 :
The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]