📜  Python|替换元组中的重复项

📅  最后修改于: 2022-05-13 01:55:29.720000             🧑  作者: Mango

Python|替换元组中的重复项

有时,在使用Python元组时,我们可能会遇到一个问题,即我们需要删除多次出现的元组元素并用一些自定义值替换重复项。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 set() + 列表推导
上述功能的组合可用于执行此特定任务。在这种情况下,我们只是初始化一个集合容器,然后在检查它是否存在于元组中之后用一个值替换重复出现的元素。

Python3
# Python3 code to demonstrate working of
# Replace duplicates in tuple
# using set() + list comprehension
 
# initialize tuple
test_tup = (1, 1, 4, 4, 4, 5, 5, 6, 7, 7)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Replace duplicates in tuple
# using set() + list comprehension
temp = set()
res = tuple(ele if ele not in temp and not temp.add(ele)
                else 'gfg' for ele in test_tup)
 
# printing result
print("Tuple after replacing values : " + str(res))


Python3
# Python3 code to demonstrate working of
# Replace duplicates in tuple
# using groupby() + loop
from itertools import groupby
 
# initialize tuple
test_tup = (1, 1, 4, 4, 4, 5, 5, 6, 7, 7)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Replace duplicates in tuple
# using groupby() + loop
res = tuple()
for key, ele in groupby(test_tup):
    res = res + ((key, ) + ('gfg', ) * (len(list(ele))-1))
 
# printing result
print("Tuple after replacing values : " + str(res))


输出 :
The original tuple is : (1, 1, 4, 4, 4, 5, 5, 6, 7, 7)
Tuple after replacing values : (1, 'gfg', 4, 'gfg', 'gfg', 5, 'gfg', 6, 7, 'gfg')


方法 #2:使用 groupby() + 循环
使用这个问题可以解决上述功能的组合。在这里,我们只是将连续的元素分组,然后将除第一个元素之外的每个元素替换为默认值。仅在连续重复的情况下有效。

Python3

# Python3 code to demonstrate working of
# Replace duplicates in tuple
# using groupby() + loop
from itertools import groupby
 
# initialize tuple
test_tup = (1, 1, 4, 4, 4, 5, 5, 6, 7, 7)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Replace duplicates in tuple
# using groupby() + loop
res = tuple()
for key, ele in groupby(test_tup):
    res = res + ((key, ) + ('gfg', ) * (len(list(ele))-1))
 
# printing result
print("Tuple after replacing values : " + str(res))
输出 :
The original tuple is : (1, 1, 4, 4, 4, 5, 5, 6, 7, 7)
Tuple after replacing values : (1, 'gfg', 4, 'gfg', 'gfg', 5, 'gfg', 6, 7, 'gfg')