numpy.unique为集列表提供错误的输出

时间:2019-11-21 14:26:11

标签: python list numpy set

我有一个列表,由...给出,

sets1 = [{1},{2},{1}]

当我使用numpy的unique在此列表中找到唯一元素时,我得到了

np.unique(sets1)
Out[18]: array([{1}, {2}, {1}], dtype=object)

可以看到,由于在输出中重复{1},结果是错误的。

当我通过使相似元素相邻来更改输入的顺序时,不会发生这种情况。

sets2 = [{1},{1},{2}]

np.unique(sets2)
Out[21]: array([{1}, {2}], dtype=object)

为什么会这样?还是我做的方式有问题?

2 个答案:

答案 0 :(得分:7)

这里发生的是np.unique函数基于NumPy的np._unique1d函数(请参见代码here),该函数本身使用.sort()方法。 / p>

现在,对每个集合中仅包含一个整数的集合列表进行排序不会,将导致列表中每个集合按集合中存在的整数值排序。这样我们就可以了(那不是我们想要的):

sets = [{1},{2},{1}]
sets.sort()
print(sets)

# > [{1},{2},{1}]
# ie. the list has not been "sorted" like we want it to

现在,正如您所指出的那样,如果已经按照想要的方式对集合列表进行了排序,那么np.unique将起作用(因为您已经预先对列表进行了排序)。

一个特定的解决方案(尽管请注意,它仅适用于每个包含单个整数的集合的列表)

np.unique(sorted(sets, key=lambda x: next(iter(x))))

答案 1 :(得分:-1)

那是因为set是不可散列的类型

{1} is {1} # will give False

如果可以将集合转换为如下所示的元组,则可以使用python collections.Counter

from collections import Counter
sets1 = [{1},{2},{1}]
Counter([tuple(a) for a in sets1])