Python|从列表中删除连续的重复项
在Python中,我们通常希望删除重复的元素,但有时对于几个特定的用例,我们需要只删除连续重复的元素。这是一项非常简单的任务,并且有一个简写方式会很有用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用groupby()
+ 列表理解
使用 groupby函数,我们可以将一起出现的元素组合为一个,并且可以连续删除所有重复项,只让一个元素在列表中。
# Python3 code to demonstrate
# removing consecutive duplicates
# using groupby() + list comprehension
from itertools import groupby
# initializing list
test_list = [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using groupby() + list comprehension
# removing consecutive duplicates
res = [i[0] for i in groupby(test_list)]
# printing result
print ("The list after removing consecutive duplicates : " + str(res))
输出:
The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9]
The list after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9]
方法 #2:使用zip_longest()
+ 列表理解
此函数可用于保留元素并使用切片删除连续元素。 zip_longest函数完成将值放在一个列表中的任务。
# Python3 code to demonstrate
# removing consecutive duplicates
# using zip_longest()+ list comprehension
from itertools import zip_longest
# initializing list
test_list = [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using zip_longest()+ list comprehension
# removing consecutive duplicates
res = [i for i, j in zip_longest(test_list, test_list[1:])
if i != j]
# printing result
print ("List after removing consecutive duplicates : " + str(res))
输出:
The original list is : [1, 4, 4, 4, 5, 6, 7, 4, 3, 3, 9]
List after removing consecutive duplicates : [1, 4, 5, 6, 7, 4, 3, 9]