用numpy数组调用lambda [英] Calling a lambda with a numpy array

查看:659
本文介绍了用numpy数组调用lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熟悉numpy的同时,我注意到了numpy数组中的一个有趣行为:

While familiarizing myself with numpy, I noticed an interesting behaviour in numpy arrays:

import numpy as np

arr = np.array([1, 2, 3])
scale = lambda x: x * 3

scale(arr) # Gives array([3, 6, 9])

将此与普通的Python列表进行对比:

Contrast this with normal Python lists:

arr = [1, 2, 3]
scale = lambda x: x * 3

scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]

我很好奇这怎么可能. numpy数组会否覆盖乘法运算符或其他内容?

I'm curious as to how this is possible. Does a numpy array override the multiplication operator or something?

推荐答案

numpy.ndarray 过载 *运算符通过定义其自己的__mul__方法.对于+-等也是如此.这允许矢量算术.

numpy.ndarray overloads the * operator by defining its own __mul__ method. Likewise for +, -, etc. This allows for vector arithmetic.

这篇关于用numpy数组调用lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆