ndarray如何使用简单的函数,如x ** 2?(How does ndarray work with a simple function, like x**2?)

编程入门 行业动态 更新时间:2024-10-25 14:32:48
ndarray如何使用简单的函数,如x ** 2?(How does ndarray work with a simple function, like 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]

How does ndarray work with a simple function, like x**2? I get this error:

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

finally...

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定义了 **运算符的行为 ,而列表元组则没有(它们可能包含任何对象,而ndarray通常用于数字)。

Because ndarray defines the behaviour for ** operator, whereas lists an tuples don't (they may contain whatever objects, whereas ndarrays are typically for numbers).

更多推荐

本文发布于:2023-08-04 08:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   函数   简单   ndarray   simple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!