Reputation: 2047
I have list of tuples called lt.
lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
I want to remove all consecutive duplicate tuple from the list. The result should look like this.
mainList = [(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
Upvotes: 0
Views: 239
Reputation: 413
You could try to make a new list, and add the elements to that list. If an element is already in the new list, don't add it.
lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
newlt = [lt[0]]
for item in range(len(lt)):
if item == 0:
continue
elif lt[item] == lt[item - 1]:
continue
else:
newlt.append(lt[item])
print(newlt)
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
Edit: New solution, this should work. It's clearly very basic.
Upvotes: -1
Reputation: 106
How about an intricate list comprehension?
[v for i, v in enumerate(lt) if i == o or v != lt[i-1]]
Upvotes: 1
Reputation: 1121486
Using the pairwise()
function from the itertools
reception section:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
mainList = [curr for curr, next in pairwise(lt) if curr != next]
This gives you a new list with all consecutive tuples removed. You could also use the itertools.groupby()
function with the default identity key:
from itertools import groupby
mainList = [k for k, g in groupby(lt)]
Demo:
>>> from itertools import tee, groupby
>>> lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
>>> def pairwise(iterable):
... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
... a, b = tee(iterable)
... next(b, None)
... return zip(a, b)
...
>>> [curr for curr, next in pairwise(lt) if curr != next]
[(1, 2), (2, 3), (3, 4), (5, 6)]
>>> [k for k, g in groupby(lt)]
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
Upvotes: 4
Reputation: 2047
lt = [ (1,2) , (1,2) , (2,3) , (3,4) , (5,6) , (7,8) , (7,8) ]
mainList = []
for t in lt:
if len(mainList) == 0:
mainList.append(t)
else:
if mainList[-1] != t:
mainList.append(t)
print(mainList)
RESULT
[(1, 2), (2, 3), (3, 4), (5, 6), (7, 8)]
Upvotes: 2