ras*_*hid 13 python numpy list set
我有一个列表,
sets1 = [{1},{2},{1}]
Run Code Online (Sandbox Code Playgroud)
当我使用numpy的在列表中找到唯一元素时unique,我得到
np.unique(sets1)
Out[18]: array([{1}, {2}, {1}], dtype=object)
Run Code Online (Sandbox Code Playgroud)
可以看出,结果是错误的,就像{1}在输出中重复的一样。
当我通过使相似元素相邻来更改输入的顺序时,不会发生这种情况。
sets2 = [{1},{1},{2}]
np.unique(sets2)
Out[21]: array([{1}, {2}], dtype=object)
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?还是我做的方式有问题?
这里发生的是该np.unique函数基于np._unique1dNumPy 的函数(请参见此处的代码),该函数本身使用该.sort()方法。
现在,对每个集合中仅包含一个整数的集合列表进行排序将不会导致列表按集合中存在的整数值排序。因此,我们将拥有(而这不是我们想要的):
sets = [{1},{2},{1}]
sets.sort()
print(sets)
# > [{1},{2},{1}]
# ie. the list has not been "sorted" like we want it to
Run Code Online (Sandbox Code Playgroud)
现在,正如您所指出的那样,如果已经按照想要的方式对集合列表进行了排序,那么np.unique它将起作用(因为您已经预先对列表进行了排序)。
那么一个特定的解决方案(尽管请注意,它仅适用于每个包含单个整数的集合的列表):
np.unique(sorted(sets, key=lambda x: next(iter(x))))
Run Code Online (Sandbox Code Playgroud)