从列表中删除重复元素以及元素本身

发布于 2024-10-20 19:01:07 字数 347 浏览 1 评论 0原文

我知道这个问题已经被问了很多次,但我不是问如何仅从列表中删除重复的元素,我也想删除重复的元素。

例如,如果我有一个列表:

x = [1, 2, 5, 3, 4, 1, 5]

我希望该列表为:

x = [2, 3, 4] # removed 1 and 5 since they were repeated

我不能使用 set,因为它将包括 15.

我应该使用计数器吗?有更好的办法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

信仰 2024-10-27 19:01:07

这应该通过 Counter 对象来完成。这是微不足道的。

from collections import Counter
x = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1]
print x

输出:

[2, 3, 4]

This should be done with a Counter object. It's trivial.

from collections import Counter
x = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1]
print x

Output:

[2, 3, 4]
你在我安 2024-10-27 19:01:07

也许这样:

[_ for _ in x if x.count(_) == 1]

编辑:就时间复杂度而言,这不是最好的方法,正如您在上面的评论中看到的那样,抱歉我的错误。

Maybe this way:

[_ for _ in x if x.count(_) == 1]

EDIT: This is not the best way in term of time complexity as you can see in the comment above, sorry my mistake.

溇涏 2024-10-27 19:01:07

更详细且 O(n) 的东西:

x = [1, 2, 2, 3, 4]

def counts_fold(acc, x):
    acc[x] = acc[x]+1 if x in acc else 1
    return acc

counts = reduce(counts_fold, x, {})

y = [i for i in x if counts[i] == 1]

print y

Something more verbose and O(n):

x = [1, 2, 2, 3, 4]

def counts_fold(acc, x):
    acc[x] = acc[x]+1 if x in acc else 1
    return acc

counts = reduce(counts_fold, x, {})

y = [i for i in x if counts[i] == 1]

print y
风尘浪孓 2024-10-27 19:01:07

怎么样

duplicates = set(x)
x = [elem for elem in x if elem not in duplicates]

这有 O(n) 而不是 O(n^2) 的优点。

编辑。确实是我的错,我一定是半睡半醒。马哈茂德的上述答案是正确的。

How about

duplicates = set(x)
x = [elem for elem in x if elem not in duplicates]

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文