简体   繁体   English

按行比较两个大小不等但维度相同的数组。 (Python)

[英]Row-wise compare two arrays of unequal sizes but same dimensions. (Python)

I have two arrays A and B of sizes (m,2) and (n,2).我有两个大小为 (m,2) 和 (n,2) 的数组 A 和 B。 A and B store the indices of non-zero elements in two different matrices P and Q. A 和 B 将非零元素的索引存储在两个不同的矩阵 P 和 Q 中。

I want to find the indices which match, so I can find which indices store non-zero values.我想找到匹配的索引,所以我可以找到哪些索引存储非零值。

Not 100% certain that this is what you're looking for, as you haven't given an example input and output, but here's what I think you want.不能 100% 确定这就是您要查找的内容,因为您没有给出输入和输出示例,但我认为这是您想要的。 Essentially, looping through each element in the first array and searching if that element exists in the second array.本质上,循环遍历第一个数组中的每个元素并搜索该元素是否存在于第二个数组中。 Then flattening the output array.然后展平输出数组。

a = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
b = [[5,7],[2,9],[13,12]]

np.shape(a)  #(6,2)
np.shape(b)  #(3,2)

# Find items common to both
c = [[[item for item in a[i] if item in b[j]] for i in range(len(a))] for j in range(len(b))]

# [[[], [], [5], [7], [], []],
#  [[2], [], [], [], [9], []],
#  [[], [], [], [], [], [12]]]

# Remove empties and flatten
c = [item for elements in c for items in elements for item in items if item != []]
#  [5, 7, 2, 9, 12]

EDIT:编辑:

Possibly a more reader-friendly method is to first flatten a and b:可能更易于阅读的方法是先将 a 和 b 展平:

a_f = [item for items in a for item in items]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

b_f = [item for items in b for item in items]
# [5, 7, 2, 9, 13, 12]

Then perform the loop through:然后执行循环:

c = [item for item in a_f if item in b_f]
# [2, 5, 7, 9, 12]

EDIT2:编辑2:

I may have misunderstood the question.我可能误解了这个问题。 If the elemnts in the arrays are two-dimensional coordinates/indicies, then you just need this:如果数组中的元素是二维坐标/索引,那么您只需要:

a = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]
b = [[5,6],[1,14],[8,7],[3,4]]

c = [item for item in a if item in b]
#  [[3, 4], [5, 6]]

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

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