如何从列表列表中删除重复项?

发布于 2025-01-19 00:29:57 字数 326 浏览 0 评论 0原文

我想从列表列表中删除重复项。我知道我们使用集合并将元素列表添加为元组的方法,因为元组是可用的。 例如:

arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

for i in arr:
   ans.add(set(i))
print(ans)

当我们打印(ANS)时,我们会得到{(1,2,4),(4,9,8),(3,2,9),(1,4,2)} 该方法删除了[1,2,4]的额外重复项,但没有[1,4,2],因为它是不同的。谁能提出一种可以删除[1,4,2]的方法,作为[1,2,4]的重复?

谢谢

I wanted to remove duplicates from a list of lists. I know the method in which we use a set and add our element lists as tuples as tuples are hashable.
ex:

arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

for i in arr:
   ans.add(set(i))
print(ans)

when we print(ans) we get {(1,2,4),(4,9,8),(3,2,9),(1,4,2)}
this method removes the extra duplicates of [1,2,4] but not [1,4,2] as it is different. can anyone suggest a method in which I can remove [1,,4,2] as a duplicate of [1,2,4]?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

怪我入戏太深 2025-01-26 00:29:57

您可以使用 frozenset 作为可哈希集:

arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

for i in arr:
    ans.add(frozenset(i))
print(ans)

或者,功能版本:

set(map(frozenset, arr))

输出:{frozenset({2, 3, 9}), freezeset({1, 2, 4}), freezeset({4, 8, 9})}

要返回列表的列表:

list(map(list,set(map(frozenset,arr))))

输出:[[9, 2, 3], [1, 2, 4], [8, 9, 4]]

注意。不保证列表和子列表中项目的顺序!

You can use a frozenset as a hashable set:

arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

for i in arr:
    ans.add(frozenset(i))
print(ans)

Or, functional version:

set(map(frozenset, arr))

output: {frozenset({2, 3, 9}), frozenset({1, 2, 4}), frozenset({4, 8, 9})}

To get back a list of lists:

list(map(list,set(map(frozenset,arr))))

output: [[9, 2, 3], [1, 2, 4], [8, 9, 4]]

NB. the order of the lists and items in sub-lists is not guaranteed!

天冷不及心凉 2025-01-26 00:29:57
arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

for i in arr:
  i.sort()
  ans.add(tuple(i))
print(ans)
arr=[[1,2,4],[4,9,8],[1,2,4],[3,2,9],[1,4,2]]
ans=set()

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