通过偶校验消除列表中的重复项



假设我们有一个列表list = ["1", "2", "1", "3", "3", "4", "3"]

我需要一种方法来删除任何重复并取消它们,以防这些重复的总数为偶数。否则,如果是奇数,则只剩下一个元素。例如,我们的列表将过滤为["2", "3", "4"]

在我的例子中,这个列表最初是在运行时添加的空元素。我需要很少的时间复杂度,因为这个列表用于实时绘制形状(在pygame中尝试我的运气)。

我遇到了这个问题的潜在解决方案:

def my_function(x):
return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist) #from https://www.w3schools.com/python/python_howto_remove_duplicates.asp

我不知道如何在不使其过于复杂的情况下实现这种抵消。谢谢您的阅读。

Using Counter. !

Counter -dict的一个子类,专门用于计算Python中可哈希对象的出现次数。

Code: Time-O(n) Space-O(n)

from collections import Counter
lis = ["1", "2", "1", "3", "1" , "3", "4", "3"]
a=Counter(lis)
res=[]
for key,value in a.items():
if value%2!=0:
res.append(key)
print(res)

输出:

['1', '2', '3', '4']

我想你在第一个例子输出中打错字了。

下面的代码由字典…!Time- O(n) Space-O(n)

代码:

lis = ["1", "2", "1", "3", "1" , "3", "4", "3"]
dic,res={},[]
for num in lis:
dic[num]=dic.get(num,0)+1

for key,value in dic.items():
if value%2!=0:
res.append(key)
print(res)  #Same output.

更新部分。

列表理解.

lis = ["1", "2", "1", "3", "1" , "3", "4", "3"]
dic={}
for num in lis:
dic[num]=dic.get(num,0)+1

res=[key for key,value in dic.items() if value%2!=0]
print(res)  #Same output.

创建一个set,它跟踪出现奇数次的所有项目。迭代输入列表中的项目:如果项目已经在集合中,则删除它。

items = ["1", "2", "1", "3", "1", "3", "4", "3"]
theSet=set()
for i in items:
if i in theSet:
theSet.remove(i)
else:
theSet.add(i)
print(theSet)

使用collections.Counter()和列表推导式:

from collections import Counter
list_ = Counter(["1", "2", "1", "3", "1", "3", "4", "3"])  # with three "1"
res = [k for k, v in list_.items() if v % 2 == 1]
print(res)

输出:

['1', '2', '3', '4']

这里有一个解决方案,应该适用于您的情况:

def remove_duplicates(lst):
result = []
counts = {}
for elem in lst:
if elem in counts:
counts[elem] += 1
else:
counts[elem] = 1
for elem, count in counts.items():
if count % 2 == 1:
result.append(elem)
return result
lst = ["1", "2", "1", "3", "1", "3", "4","4","3"]
#here 4 is in list two times(even)
result = remove_duplicates(lst)
print(result)

该解决方案首先使用字典计算列表中每个元素出现的次数。然后,它遍历字典并将出现次数为奇数的元素追加到结果列表中。这将为您提供所需的行为,即取消重复项的偶数出现,并在重复项的数量为奇数时仅保留一个元素。

此解决方案的时间复杂度应为O(n),因为它通过列表迭代一次来计算出现次数,然后再次处理计数。这应该使它适合在实时应用程序中使用。

最新更新