Calling a lambda with a numpy array

2020-07-10 09:20发布

问题:

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])

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]

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

回答1:

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



回答2:

Its all about Overriding operators in numpy

You can learn numpy.arry here

Let us focus on your lamda function for each;

1. numpy array :

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

this takes each element from array

2. normal list:

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



回答3:

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.

code example:

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

result:

list
numpy.ndarray