gpt4 book ai didi

python - 添加列表和 NumPy 数字

转载 作者:太空狗 更新时间:2023-10-29 17:57:46 26 4
gpt4 key购买 nike

如果您向列表中添加一个整数,您会收到列表的 __add__ 函数引发的错误(我想):

>>> [1,2,3] + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list

如果将列表添加到 NumPy 数组,我假设 NumPy 数组的 __add__ 函数将列表转换为 NumPy 数组并添加列表

>>> np.array([3]) + [1,2,3]
array([4, 5, 6])

但是下面会发生什么?

>>> [1,2,3] + np.array([3])
array([4, 5, 6])

列表如何知道如何处理 NumPy 数组的加法?

最佳答案

list 不知道如何处理 NumPy 数组的加法。即使在 [1,2,3] + np.array([3]) 中,处理加法的也是 NumPy 数组。

作为documented in the data model :

  • For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception:

  • Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base’s __rop__() method, the right operand’s __rop__() method is tried before the left operand’s __op__() method.

当你做的时候

[1,2,3] + np.array([3])

内部调用的是

np.array([3]).__radd__([1,2,3])

关于python - 添加列表和 NumPy 数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151072/

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