如何从列表列表中删除重复项?
我想从列表列表中删除重复项。我知道我们使用集合并将元素列表添加为元组的方法,因为元组是可用的。 例如:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
frozenset
作为可哈希集:或者,功能版本:
输出:
{frozenset({2, 3, 9}), freezeset({1, 2, 4}), freezeset({4, 8, 9})}
要返回列表的列表:
输出:
[[9, 2, 3], [1, 2, 4], [8, 9, 4]]
注意。不保证列表和子列表中项目的顺序!
You can use a
frozenset
as a hashable set:Or, functional version:
output:
{frozenset({2, 3, 9}), frozenset({1, 2, 4}), frozenset({4, 8, 9})}
To get back a list of lists:
output:
[[9, 2, 3], [1, 2, 4], [8, 9, 4]]
NB. the order of the lists and items in sub-lists is not guaranteed!