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..
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', '')]
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.