2015-05-19 92 views
3

有人可以解釋爲什麼會出現以下情況嗎?我的用例是我有一個python列表,其元素都是numpy的ndarray對象,我需要搜索列表以查找特定ndarray obj的索引。查找列表中的numpy數組索引

最簡單的例子:

>>> import numpy as np 
>>> a,b = np.arange(0,5), np.arange(1,6) 
>>> a 
array([0, 1, 2, 3, 4]) 
>>> b 
array([1, 2, 3, 4, 5]) 
>>> l = list() 
>>> l.append(a) 
>>> l.append(b) 
>>> l.index(a) 
0 
>>> l.index(b) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

爲什麼l找到a的指標,但不是b

+0

什麼是這個代碼怎麼回事? – WuJo

+3

通常,當您嘗試在'numpy'布爾數組(或列表)上執行Python布爾操作('in','if')時會出現此錯誤。例如'如果[真,假......]:'。在這裏,我懷疑一個'index'匹配id,另一個嘗試'=='測試。似乎取決於列表的構建方式。 – hpaulj

+0

涉及'numpy'數組的列表索引操作可能不是一個好主意。 – hpaulj

回答

4

應用在https://stackoverflow.com/a/17703076/901925想法(見相關sidebare)

[np.array_equal(b,x) for x in l].index(True) 

應更可靠。它確保了一個正確的數組到數組的比較。

[id(b)==id(x) for x in l].index(True)如果你想確保它比較ids。

0

的想法是numpy的數組轉換成列表和改造問題在其他列表中找到一個列表:

def find_array(list_of_numpy_array,taregt_numpy_array): 
    out = [x.tolist() for x in list_of_numpy_array].index(taregt_numpy_array.tolist()) 
    return out