[英]How can I see if a list of tuples contains a specific tuple by knowing the values in this tuple?
[英]how can i change my list which contains tuple data, to duplicating tuple removed list
我的清單是這樣的
list = [('N',''),('N',''),('K','asdf'),('K','asw'),('S','aqq'),('N',''),('N',''),('N','')]
我想將此列表更改為
list_1 = [('N',''),('K','asdf'),('K','asdf'),('S','aqq'),('N','')]
僅應刪除重復的N。
您可以使用itertools.groupby
並使用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', '')]
編輯 :
如果您只想刪除以'N'
開頭的元組的連續重復項,則可以使用
>>> [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', '')]
只需使用set即可刪除重復項
>>> 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')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.