2012-08-27 26 views
2

ndarray如何使用一個簡單的函數,如x ** 2?我得到這個錯誤:ndarray如何使用一個簡單的函數,如x ** 2?

arr = array([3,4,5]) 
f = lambda x: x**2 
print f(arr)  # works, but how? 
print f(3)  # works 
print f([3,4,5]) # will not work 
#TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int' 
print f((3,4,5)) # will not work 
#TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int' 

>>>f(arr) 
#[ 9 16 25] 
>>>f(3) 
#9 

終於...

class Info(object): 
    def __init__(self,x): 
     self.a = x< 
    def __pow__(self,x): 
     for i in xrange(len(self.a)): 
      self.a[i]**=x 
     return self 

a = Info([3,4]) 
f = lambda x:x**2 
a = f(a) 
print a.a 
[9, 16] 

回答

5

因爲ndarray defines the behaviour**運營商,而列表的一個元組沒有(它們可能含有的任何對象,而ndarrays通常爲數字) 。

+0

感謝您的幫助! –

相關問題