如何在没有多个for循环的情况下从nd numpy数组中删除一对反向元素



例如:

原件:[[0 2][0 3][1 4][2 0][2 3][3 0][3 2][4 1]]

编辑时间:[[0 2][0 3][1 4][2 3]]

一个选项:排序并获取唯一值:

a = np.array([[0, 2], [0, 3], [1, 4], [2, 0], [2, 3], [3, 0], [3, 2], [4, 1]])
out = np.unique(np.sort(a), axis=0)

输出:

array([[0, 2],
[0, 3],
[1, 4],
[2, 3]])

如果您想确保保留原始(未排序(数据:

# different example, note the initial [2, 0]
a = np.array([[2, 0], [0, 3], [1, 4], [2, 0], [2, 3], [3, 0], [3, 2], [4, 1]])
idx = np.unique(np.sort(a), axis=0, return_index=True)[1]
a[idx]

输出:

array([[2, 0],
[0, 3],
[1, 4],
[2, 3]])

一个for循环的快速简单方法:

s = [[0, 2], [0, 3], [1, 4], [2, 0], [2, 3], [3, 0], [3, 2], [4, 1]]

result = []
result.append(s[0])
for x in s:
if not([x[-1],x[0]] in result) and not(x  in result):
result.append(x)
result

输出:

[[0, 2], [0, 3], [1, 4], [2, 3]]

最新更新