ndarray如何使用简单的函数,如x ** 2?

时间:2012-08-27 07:46:54

标签: python numpy

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]

1 个答案:

答案 0 :(得分:5)

因为**运算符的ndarray defines the behaviour,而列表元组则没有(它们可能包含任何对象,而ndarrays通常用于数字)。