gpt4 book ai didi

python - ndarray 如何处理一个简单的函数,比如 x**2?

转载 作者:行者123 更新时间:2023-11-28 22:02:02 24 4
gpt4 key购买 nike

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]

最佳答案

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

关于python - ndarray 如何处理一个简单的函数,比如 x**2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com