【发布时间】:2018-09-13 21:10:56
【问题描述】:
假设我有一个由元组组成的列表:
stList = [('NJ', 'Burlington County', '12/21/2017'),
('NJ', 'Burlington County', '12/21/2017'),
('NJ', 'Burlington County', '12/21/2017'),
('VA', 'Frederick County', '2/13/2018'),
('MD', 'Montgomery County', '8/7/2017'),
('NJ', 'Burlington County', '12/21/2017'),
('NC', 'Lee County', '1/14/2018'),
('NC', 'Alamance County', '11/28/2017'),]
我想遍历每个项目(元组),如果它已经存在,请将其从stList 中删除。
for item in stList:
if item in stList:
stList.remove(item)
这并不完全有效。基本上,当我运行这个时,如果元组中的 any 项目也在列表中,它会删除该项目,所以我得到这个:
[('NJ', 'Burlington County', '12/21/2017'),
('VA', 'Frederick County', '2/13/2018'),
('NJ', 'Burlington County', '12/21/2017'),
('NC', 'Alamance County', '11/28/2017')]
有什么更好的方法来解决这个问题?
【问题讨论】:
标签: list tuples comparison python-3.6