簡體   English   中英

遍歷列表中的元組

[英]Iterating through tuples in a 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))

如果只需要一個可迭代的對象,而無需索引stList ,則甚至可以將其保留為一個set對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM