Python 使用 numpy 数组调用 lambda

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42920602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:16:14  来源:igfitidea点击:

Calling a lambda with a numpy array

pythonarraysnumpy

提问by peco

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

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

import numpy as np

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

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

Contrast this with normal Python lists:

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

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

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

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

我很好奇这怎么可能。numpy数组是否覆盖乘法运算符或其他什么?

采纳答案by Crispin

numpy.ndarrayoverloadsthe *operator by defining its own __mul__method. Likewise for +, -, etc. This allows for vector arithmetic.

numpy.ndarray重载*操作者通过定义自己的__mul__方法。对于+-等也是如此。这允许进行向量算术。

回答by Shivkumar kondi

Its all about Overridingoperators in numpy

全部是关于在 numpy 中覆盖运算符

You can learn numpy.arry here

你可以在这里学习 numpy.arry

Let us focus on your lamda function for each;

让我们专注于您的 lamda 函数;

1. numpy array :

1. numpy 数组:

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

this takes each element from array

这从数组中获取每个元素

2. normal list:

2.正常名单:

a =[1,2,3]
type(a)
scale = lambda x: x * 3 
scale(a)

this takes full list as x and multiplies the list here itself

这将完整列表作为 x 并在此处乘以列表本身

回答by ibezito

These are two different objects which behaves differently when you use * operator on them.

这是两个不同的对象,当您对它们使用 * 运算符时,它们的行为会有所不同。

  1. In the first case you generate a numpy array. In this case, * operator was overloaded for performing multiplication. i.e. every element will be multiplied by 3.

  2. In the second case you generate a list. In this case the * operator is treated as a repetition operator, and the entire list is repeated 3 times.

  1. 在第一种情况下,您生成一个 numpy 数组。在这种情况下,* 运算符被重载以执行乘法。即每个元素都将乘以 3。

  2. 在第二种情况下,您生成一个列表。在这种情况下, * 运算符被视为重复运算符,整个列表重复 3 次。

code example:

代码示例:

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

result:

结果:

list
numpy.ndarray