繁体   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