1

My list is like this

list = [('N',''),('N',''),('K','asdf'),('K','asw'),('S','aqq'),('N',''),('N',''),('N','')]

I want change this list to

list_1 = [('N',''),('K','asdf'),('K','asdf'),('S','aqq'),('N','')]

only duplicated N should be removed..

Arcanes
  • 31
  • 6
  • possible duplicate of [Removing elements that have consecutive dupes](http://stackoverflow.com/questions/5738901/removing-elements-that-have-consecutive-dupes) – Bhargav Rao Jun 09 '15 at 12:02

2 Answers2

2

You can use itertools.groupby and grab the first item out of each group using next.

>>> import itertools
>>> l = [('N',''),('N',''),('K','asdf'),('K','asw'),('S','aqq'),('N',''),('N',''),('N','')]
>>> [next(group) for key, group in itertools.groupby(l)]
[('N', ''), ('K', 'asdf'), ('K', 'asw'), ('S', 'aqq'), ('N', '')]

Edit:
If you just want to remove the consecutive duplicates of the tuples starting with 'N' then you can use

>>> [key if key[0] == 'N' else list(itertools.chain.from_iterable(group)) for key, group in itertools.groupby(l)]
[('N', ''), ['K', 'asdf'], ['K', 'asw'], ['S', 'aqq'], ('N', '')]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
-1

simply you can use set to remove duplicates

>>> old_list
[('N', ''), ('N', ''), ('K', 'asdf'), ('K', 'asw'), ('S', 'aqq'), ('N', ''), ('N', ''), ('N', '')]
>>> list_1 = list((set(old_list)))
>>> list_1
[('K', 'asdf'), ('N', ''), ('K', 'asw'), ('S', 'aqq')]
Ravi Kumar
  • 1,769
  • 2
  • 21
  • 31