从python中的multi-d数组中删除重复的条目 [英] removing duplicate entries from multi-d array in python
本文介绍了从python中的multi-d数组中删除重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维数组
xx=[[a,1],[b,2],[c,3]]
现在,我正在尝试从中删除重复的条目.对于简单的一维数组,像
Now I'm trying to remove duplicate entries from it. For simple 1-D array, simple code like
xx=list(set(xx))
会工作.但是尝试在二维元素上设置会出现错误
would work. But trying set on 2-d elements gives an error
temp = set(xx)
TypeError: unhashable type: 'list'
一种解决方法是序列化xx个元素,然后在新数组上执行list(set()),然后再次反序列化所有元素.
One workaround would be to serialize xx elements, and then do a list(set()) on new array and then unserialize all the elements back again.
python中有什么解决方案吗?
Is there any solution in python?
推荐答案
将元素转换为元组,然后使用set
.
Convert elements to tuple and then use set
.
>>> xx=[['a',1],['b',2],['c',3],['c',3]]
>>> set(tuple(element) for element in xx)
set([('a', 1), ('b', 2), ('c', 3)])
>>>
与列表不同,可以对哈希进行哈希处理.因此.完成后,将元素转换回列表.将所有内容放在一起:
Tuples, unlike lists, can be hashed. Hence. And once you are done, convert the elements back to list. Putting everything together:
>>> [list(t) for t in set(tuple(element) for element in xx)]
[['a', 1], ['b', 2], ['c', 3]]
这篇关于从python中的multi-d数组中删除重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文