从python中的多维数组中删除重复条目 [英] removing duplicate entries from multi-d array in python
问题描述
我有一个二维数组
xx=[[a,1],[b,2],[c,3]]
现在我正在尝试从中删除重复的条目.对于简单的一维数组,简单的代码如
xx=list(set(xx))
会起作用.但是在二维元素上尝试设置会出错
temp = set(xx)类型错误:不可散列的类型:列表"
一种解决方法是序列化 xx 个元素,然后在新数组上执行 list(set()),然后再次反序列化所有元素.
python 有什么解决办法吗?
将元素转换为元组,然后使用set
.
与列表不同,元组可以散列.因此.完成后,将元素转换回列表.将所有内容放在一起:
<预><代码>>>>[list(t) for t in set(tuple(element) for element in xx)][['a', 1], ['b', 2], ['c', 3]]I have a 2-d array
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'
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.
Is there any solution in python?
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中的多维数组中删除重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!