【问题标题】:How to find the index with the same value in three arrays如何在三个数组中找到具有相同值的索引
【发布时间】:2018-02-23 04:01:21
【问题描述】:

数据形状是:

(675369, 3)
(675369, 3)
(670877, 3)

axis=1的含义是xyz的坐标值。

所以想在三个数组中获得相同的xyz 值。

如何在三个数组中找到相同值的索引?

【问题讨论】:

  • 你的代码中是如何定义的?
  • 你的问题不清楚!
  • 请给出示例输入输出

标签: python arrays numpy


【解决方案1】:

如果所有数组长度相同你可以遍历它们直到你找到所有 3 的索引都相同。

例如 (python, O(n))

def findMatchingIndex(a, b, c):
    for index, val in enumerate(a): # enumerate through a to get the index of the item we are looking at...
        if val == b[index] and b[index] == c[index]: # if a = b and b = c then a = c
            return index # return the first shared index we find
    return -1 # or -1 for no index.

# for example...
findMatchingIndex([1, 2, 3], [2, 2, 1], [3, 2, 1]) # = 1
findMatchingIndex([1, 2, 3], [4, 5, 6], [3, 2, 1]) # = -1

编辑

但是,如果它们的长度不同,您将希望使用最小公分母,即最小长度。

def findMatchingIndex2(a, b, c): 
    # get the smallest size
    size = sorted( [ len(a), len(b), len(c) ] )[0] # sort the lengths of the arrays and get the smallest/first one

    for index in range (0, size): # go until the smallest array is done
        if a[index] == b[index] and b[index] == c[index]: # if a = b and b = c then a = c
            return index # return the first shared index we find
    return -1 # or -1 for no index.

# for example...
findMatchingIndex2([1, 2, 3], [2, 2, 1], [3, 2, 1]) # = 1
findMatchingIndex2([1, 2, 3], [2, 3, 3], [3, 3, 3]) # = 2
findMatchingIndex2([1, 2, 3], [2, 3, 3], [3, 3]) # = -1

【讨论】:

  • 我同意,如果它们的大小不同,此算法将失败。我理解的问题是如何在 XYZ 网格中找到一个匹配的索引,其中所有 3 个数组都具有相同的长度(因为它们是匹配对)
  • @chrisz 我创建了另一个支持各种大小数组的版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2017-10-04
  • 2018-10-13
  • 1970-01-01
相关资源
最近更新 更多