首页 > 解决方案 > 遍历列表中的元组

问题描述

假设我有一个由元组组成的列表:

 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')]

有什么更好的方法来解决这个问题?

标签: listtuplescomparisonpython-3.6

解决方案


您可以直接比较元组。

所有条目匹配的元组将被视为相等。

>>> ('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对象。


推荐阅读