[英]Removing duplicates from a list but returning the same list
I need to remove the duplicates from a list but return the same list. 我需要从列表中删除重复项,但返回相同的列表。 So options like:
所以像这样的选项:
return list(set(list))
will not work for me, as it creates a new list instead. 不适用于我,因为它会创建一个新列表。
def remove_extras(lst):
for i in lst:
if lst.count(i)>1:
lst.remove(i)
return lst
Here is my code, it works for some cases, but I dont get why it does not work for remove_extras([1,1,1,1]), as it returns [1,1] when the count for 1 should be >1. 这是我的代码,它在某些情况下有效,但是我不明白为什么它不适用于remove_extras([1,1,1,1]),因为当1的计数应为>时,它将返回[1,1] 1。
You can use slice assignment to replace the contents of the list after you have created a new list. 创建新列表后,可以使用切片分配来替换列表的内容。 In case order of the result doesn't matter you can use
set
: 如果结果的顺序无关紧要,则可以使用
set
:
def remove_duplicates(l):
l[:] = set(l)
l = [1, 2, 1, 3, 2, 1]
remove_duplicates(l)
print(l)
Output: 输出:
[1, 2, 3]
You can achieve this using OrderedDict
which removes the duplicates while maintaining order of the list. 您可以使用
OrderedDict
做到这一点,该命令在保留列表顺序的同时删除重复项。
>>> from collections import OrderedDict
>>> itemList = [1, 2, 0, 1, 3, 2]
>>> itemList[:]=OrderedDict.fromkeys(itemList)
>>> itemList
[1, 2, 0, 3]
This has a Runtime : O(N) 这有一个运行时: O(N)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.