为什么numpy数组的行为是这样的

I was working on a mini project which I intended to use pure Python without any external library. But at a certain point, I got a TypeError like this TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'. It was as a result of trying to directly square up all elements in a list like this:

my_list = [0, 7, 2, 9] 
print(my_list ** 2)
import numpy as np
my_list = np.array([0, 7, 2, 9])
print(my_list ** 2)# prints array[0, 49, 4, 9]
评论
  • 维她命
    维她命 回复

    np.ndarray defines its own dunder methods for operators such as __pow__. That's how it manages to handle those operations elementwise. With builtin lists you can use a list comprehension instead:

    [x**2 for x in my_list]
    

    您还可以定义自己的类来暴露此类自定义行为:

    >>> class PowList(list):
    ...     def __pow__(self, other):
    ...         return [x**2 for x in self]
    ... 
    >>> my_list = PowList([1, 2, 3, 4, 5])
    >>> my_list ** 2
    [1, 4, 9, 16, 25]