2016-12-04 175 views
1

我是python的新手。这是我的问题。查找两个高维numpy阵列之间的相互元素

import numpy as np 

def neighbors(indexset, i,j): 
    temp = np.array([[i-1,j],[i+1,j],[i,j-1],[i,j+1]]) 
    for ele in temp: 
     if ele in indexset: 
      print(ele) 

indexset = np.array([[0,1],[1,1],[2,1],[3,1]]) 
neighbors(indexset, 0,0) 

当我运行此我得到的值,我不明白

neighbors(indexset, 0,0) 
[1 0] 
[ 0 -1] 
[0 1] 

我在做什么错?为什么不只返回[0,1]?

+0

哪些是样品中二高维numpy的阵列? – Divakar

+0

的目标是找到temp和indexset的共享元素 – kevinkayaks

回答

2

我认为你会得到结果结果,因为ele in temp只适用于ele是标量。它使用numpy函数__contains__,相当于(a==b).any()。如果你这样做与Python列表,而不是numpy的阵列,它的工作原理:

def neighbors(indexset, i,j): 
    temp = [[i-1,j],[i+1,j],[i,j-1],[i,j+1]] 
    for ele in temp: 
     if ele in indexset: 
      print(ele) 

indexset = [[0,1],[1,1],[2,1],[3,1]] 
neighbors(indexset, 0,0) 

将打印[0,1]预期。如果indexset始终是一个numpy的数组,你可以使用tolist

import numpy as np 

def neighbors(indexset, i,j): 
    temp = [[i-1,j],[i+1,j],[i,j-1],[i,j+1]] 
    for ele in temp: 
     if ele in indexset.tolist(): 
      print(ele) 

indexset = np.array([[0,1],[1,1],[2,1],[3,1]]) 
neighbors(indexset, 0,0) 
+0

谢谢!我看到代码在列表上工作。不过,我认为indexset必须是一个numpy数组。 与tolist建议的修订版不起作用。 我得到 ValueError异常:具有多于一个元素的数组的真值是不明确的。使用a.any()或a.all()。 我想我需要比“中” – kevinkayaks

+0

使用,我得到的输出作为唯一上榜的实现同一种不同的方法。你有没有用我在答案的第二部分所写的内容?因为'temp'也需要成为一个列表,它在我的函数中。也许你在'tolist'方法的版本中将'temp'作为一个numpy数组? –

+0

是的,我可以通过在'neighbours'函数中将'temp'设置为一个numpy数组,并且只在'indexset'上使用'tolist'来复制'ValueError'。只要将'temp = np.array([[i-1,j],[i + 1,j],[i,j-1],[i,j + 1]])'改为'temp = [[ i-1,j],[i + 1,j],[i,j-1],[i,j + 1]]'在'neighbours'版本中使用'tolist'。 –