繁体   English   中英

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

[英]How can I remove one of the reverse pairs of elements from an nd numpy array without multiple for loops?

例如:

原文:[[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)

output:

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]

output:

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

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM