list - 遍历列表中的元组
问题描述
假设我有一个由元组组成的列表:
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)
这并不完全有效。基本上,当我运行它时,如果元组中的任何项目也在列表中,它会删除该项目,所以我得到这个:
[('NJ', 'Burlington County', '12/21/2017'),
('VA', 'Frederick County', '2/13/2018'),
('NJ', 'Burlington County', '12/21/2017'),
('NC', 'Alamance County', '11/28/2017')]
有什么更好的方法来解决这个问题?
解决方案
您可以直接比较元组。
所有条目匹配的元组将被视为相等。
>>> ('NJ', 'Burlington County', '12/21/2017') == ('NJ', 'Burlington County', '12/21/2017')
>>> True
>>> ('NJ', 'Burlington County', '12/21/2017') == ('NJ', 'Burlington County', '1/21/2017')
>>> False
不要从您正在迭代的集合中删除项目。
除非您知道删除是如何完成的并且您正在正确执行,否则这可能会产生意外行为。那是一个不同的故事。
这里有几个选项。
seen = set()
result = []
for item in stList:
# Tuple can be compared directly to other tupled in `seen`.
if item not in seen:
seen.add(item)
result.append(item)
stList = result
另一种可能是
seen = set()
# Use a list to preserve ordering. Change to set if that does not matter.
first_seen = []
for i, item in enumerate(stList):
if item not in seen:
seen.add(item)
first_seen.append(i)
stList = [stList[i] for i in first_seen]
编辑
第二个想法第二个选项不如第一个好,除非您出于某种原因需要索引(即,它们可以被重用于其他任务),因为result
在第一种情况下存储引用而不是元组的副本,所以它会产生的内存或多或少与将索引存储到stList
.
如果订购无关紧要
stList = list(set(stList))
如果您只想要一个可迭代且不需要 index stList
,那么您甚至可以将其保留为set
对象。
推荐阅读
- python-3.x - 如何安装 sent2vec 模块?
- c# - 在 MVC 中使用不同功能的同一行中的 2 个提交按钮
- flutter - 在 ios 上进行代码签名时无法在 Codemagic 上创建身份验证会话
- django - 禁止直接分配到多对多集合的前端。改用interested_time.set()
- javascript - Ngx-Charts 显示所有 x 轴值但交替的 x 轴标签
- python - 我希望我的对象继续移动,但它不起作用
- python - 如何将 DataFrame 转换为嵌套字典,子元素和父元素中都存在相同的列
- amazon-web-services - 从 VPC 内的 lambda 函数访问 AWS Data Exchange 时返回超时错误
- python - python程序/可执行文件是可移植的吗?
- c# - 实现接口的 Blazor 组件列表