从列表中删除重复元素以及元素本身
我知道这个问题已经被问了很多次,但我不是问如何仅从列表中删除重复的元素,我也想删除重复的元素。
例如,如果我有一个列表:
x = [1, 2, 5, 3, 4, 1, 5]
我希望该列表为:
x = [2, 3, 4] # removed 1 and 5 since they were repeated
我不能使用 set
,因为它将包括 1
和 5.
我应该使用计数器
吗?有更好的办法吗?
I know this question has been asked lots of times, but I am not asking how to remove duplicate elements from a list only, I want to remove the duplicated element as well.
For example, if I have a list:
x = [1, 2, 5, 3, 4, 1, 5]
I want the list to be:
x = [2, 3, 4] # removed 1 and 5 since they were repeated
I can't use a set
, since that will include 1
and 5
.
Should I use a Counter
? Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该通过 Counter 对象来完成。这是微不足道的。
输出:
This should be done with a Counter object. It's trivial.
Output:
也许这样:
编辑:就时间复杂度而言,这不是最好的方法,正如您在上面的评论中看到的那样,抱歉我的错误。
Maybe this way:
EDIT: This is not the best way in term of time complexity as you can see in the comment above, sorry my mistake.
更详细且 O(n) 的东西:
Something more verbose and O(n):
怎么样
这有 O(n) 而不是 O(n^2) 的优点。
编辑。确实是我的错,我一定是半睡半醒。马哈茂德的上述答案是正确的。
How about
This has the advantage of being O(n) instead of O(n^2).
Edit. Indeed my bad, I must have been half asleep. Mahmoud's answer above is the correct one.