Reputation: 33223
Say, I have a list like below:
[(2, 1), (1, 0), (1, 0), (1,0), (2,1), (2, 1)]
I want to remove duplicate consecutive tuples. So in above example, it should return:
[(2, 1), (1, 0), (2, 1)]
Upvotes: 1
Views: 90
Reputation: 6748
a=[(2, 1), (1, 0), (1, 0), (1,0), (2,1), (2, 1)]
a=[elem for count,elem in enumerate(a) if elem!=a[count-1] or count==0]
How about this list comprehension
Upvotes: 1
Reputation: 1576
You can use itertools.groupby
:
from itertools import groupby
x = [(2, 1), (1, 0), (1, 0), (1, 0), (2, 1), (2, 1)]
x_grouped = [i for i, j in groupby(x)]
# [(2, 1), (1, 0), (2, 1)]
Upvotes: 10
Reputation: 1121486
You can use a generator that only yields elements that are not equal to the preceding one:
def filter_consecutive_duplicates(it):
prev = object() # sentinel object, won't be equal to anything else
for elem in it:
if elem != prev:
yield elem
prev = elem
Demo:
>>> list(filter_consecutive_duplicates([(2, 1), (1, 0), (1, 0),(1,0),(2,1), (2, 1)]))
[(2, 1), (1, 0), (2, 1)]
Upvotes: 6