在Python中同时从列表中删除重复项

在Python中同时从列表中删除重复项,python,Python,所以我在研究一个问题,给定一个元组列表,我必须返回一个只包含元组第一个元素不重复的元素的新列表。删除重复项没有问题,但我的问题是在找到重复项后立即删除原始元素。例如 inputList = [("test0", 20), ("test1", 25), ("test0", 30)] 这应该会回来 [("test1", 25)] 在我遇到麻烦之后,我已经让它工作了,但是我担心我的代码不好,并且有一种更简单的方法来执行我所做的事情。 我是通过先删除重复项来完成的 visited = set() m

所以我在研究一个问题,给定一个元组列表,我必须返回一个只包含元组第一个元素不重复的元素的新列表。删除重复项没有问题,但我的问题是在找到重复项后立即删除原始元素。例如

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)
然后,我根据标记的列表检查新的输出列表

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

第一次计算第一个元素在列表中出现的次数。为此,我们使用字典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]

您只需使用如下列表理解即可:

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

outputList = [(x, y) for x, y in inputList if list1.count(x) == 1]
希望它能有所帮助:

使用a来计算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)]

如果还没有,则将其添加到输出中。如果它已经存在,请删除它并将其列入黑名单,以避免再次添加它

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)