2014-09-02 113 views
0

我想比較numpy數組與列表.... 因爲我是新來的python,我不知道numpy數組 我想知道numpy數組的應用 請幫助理解numpy數組。numpy模塊陣列與列表比較

>>> from numpy import * 
>>> res1 = [] 
>>> res2 = array([]) 
>>> if res1 == res2: 
... print 'hi' 
... else: 
... print 'bye' 
... 
bye 

>>> res1 = [1] 
>>> res2 = array([1]) 
>>> if res1 == res2: 
... print 'hi' 
... else: 
... print 'bye' 
... 
hi 
>>> res1 = [1,2] 
>>> res2 = array([1, 2]) 
>>> if res1 == res2: 
... print 'hi' 
... else: 
... print 'bye' 
... 
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() 

中的任何一個,請幫助爲什麼我收到值誤差

回答

0

比較res1 == res2創建布爾值的新陣列,它代表的名單和數組內容元素之比較:

>>> res1 == res2 
array([ True, True], dtype=bool) 

由於錯誤消息告訴您,您不能直接爲數組指定真值,因此您需要測試all項是否爲True

>>> np.all(res1 == res2) 
True 

這僅是因爲你的清單,排列形狀相同:

>>> a = np.array([1, 2, 3]) 
>>> b = [3, 2] 
>>> a == b 
False 

請注意,我用import numpy as np而非from numpy import * - 這意味着我並不如覆蓋內置allnumpy的版本。

+0

謝謝你,它幫了我很多 – shrum 2014-09-02 12:37:50

0

您可以使用numpy.array_equal(a1, a2)進行比較拖拽numpy陣列!

如果兩個數組具有相同的形狀和元素,則爲true,否則爲False。

DEMO:

>>> np.array_equal(np.array([1, 2]), np.array([1, 2])) 
True 
>>> np.array_equal([1, 2], [1, 2, 3]) 
False 
+0

謝謝您的雁 – shrum 2014-09-02 12:39:52

+0

以及COM!所以不要忘記投票!) – Kasramvd 2014-09-02 12:53:51