簡體   English   中英

在 Python 中一起從列表中刪除重復項

[英]Removing duplicates from list all together in Python

所以我正在研究一個問題,在給定一個元組列表的情況下,我必須返回一個新列表,該列表只包含元組的第一個元素不重復的元素。 刪除重復項我沒有問題,但我的問題是一旦發現重復項就刪除原始元素。 例如。

inputList = [("test0", 20), ("test1", 25), ("test0", 30)]

這應該返回

[("test1", 25)]

在我的麻煩讓它工作之后,我擔心我的代碼很糟糕,並且有一種更簡單的方法來執行我所做的事情。 我已經通過首先刪除重復項來完成它

visited = set()
marked = []
output = []
for key, value in resList:
    if not key in visited:
        visited.add(key)
        output.append((key, value))
    else:
        marked.append(key)

然后我對照我的標記列表檢查我的新 output 列表

resList = []
for mark in marked:
    for i in range(len(output)):
        if mark != output[i][0]
            resList.append(output[i])

您可以像這樣簡單地使用列表理解來做到這一點:

list1 = [x[0] for x in inputList]

outputList = [(x, y) for x, y in inputList if list1.count(x) == 1]

希望能幫助到你:)

首先計算第一個元素在列表中出現的次數。 為此,我們使用字典d 然后使用簡單的列表推導。

d = dict()
for x, y in inputList:
  d[x] = d.get(x, 0) + 1
outputList = [(x, y) for x, y in inputList if d[x] == 1]

使用Counter計算inputList中的出現次數,然后過濾掉任何多次出現的項目。

from collections import Counter

count = Counter(t[0] for t in inputList)
result = [t for t in inputList if count[t[0]] == 1]

print(result)  # -> [('test1', 25)]

如果 output 尚不存在,請將其添加到。 如果它已經存在,請將其刪除並將其列入黑名單(以避免再次添加)。

inputList = [("test0", 20), ("test1", 25), ("test0", 30)]

removed = set()
output = []
for key, value in inputList:
    keyfound = False
    for refkey, refvalue in output:
        if key == refkey:
            keyfound = True
            removed.add(key)
            output.remove((refkey, refvalue))
    if keyfound == False and key not in removed:
        output.append((key, value))

print(output)

暫無
暫無

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

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