杰瑞科技汇

multiply在Python中具体怎么用?

Python 的核心语言里没有一个叫做 multiply 的内置函数

multiply在Python中具体怎么用?-图1
(图片来源网络,侵删)

你提到的 multiply,通常指的是以下两种情况之一,它们都非常重要:

  1. 来自 operator 模块的 operator.multiply 函数:这是最常见的情况,用于获取“乘法”这个操作本身。
  2. 来自第三方库 NumPynumpy.multiply 函数:用于在 NumPy 数组之间进行高效的元素级乘法。

下面我们分别详细解释这两种情况。


operator.multiply (来自标准库)

这是 operator 模块中的一个函数,它的作用是返回一个函数,这个函数的功能就是执行乘法运算

听起来有点绕,但理解了之后就很简单,它的本质是*将“乘法”这个操作从一个运算符(``)变成一个可以被传递、被调用的函数对象**。

multiply在Python中具体怎么用?-图2
(图片来源网络,侵删)

为什么需要 operator.multiply

直接使用 运算符进行乘法非常直观,但在某些高级编程场景中,我们需要一个代表“乘法”这个行为的函数对象,主要有以下几个原因:

  • 高阶函数:当函数需要接受另一个函数作为参数时,operator.multiply 就派上用场了。
  • 代码可读性:在某些情况下,使用函数名(如 multiply)比使用运算符()更能表达意图。
  • 动态调用:你可以根据变量来决定执行哪种运算。

示例

基本用法

operator.multiply(a, b) 的效果和 a * b 完全一样。

import operator
# 基本乘法
result = operator.multiply(5, 3)
print(result)  # 输出: 15
# 浮点数乘法
result_float = operator.multiply(4.5, 2)
print(result_float)  # 输出: 9.0
# 字符串重复(乘法在字符串上的特殊含义)
result_str = operator.multiply("hello", 3)
print(result_str)  # 输出: hellohellohello

作为高阶函数的参数

这是 operator 模块最常见的用途,比如在 map(), sorted(), functools.reduce() 等函数中。

import operator
from functools import reduce
# 示例 1: 使用 map() 对一个列表的每个元素乘以 2
numbers = [1, 2, 3, 4, 5]
# map(function, iterable)
# 我们需要一个函数来执行 "乘以2" 的操作
doubled = list(map(lambda x: operator.multiply(x, 2), numbers))
print(doubled)  # 输出: [2, 4, 6, 8, 10]
# 示例 2: 使用 reduce() 计算一个列表所有元素的乘积
numbers = [1, 2, 3, 4, 5]
# reduce(function, iterable) 会把函数作用在序列的元素上
#  (((1*2)*3)*4)*5
product = reduce(operator.multiply, numbers)
print(product)  # 输出: 120
# 对比一下,如果不用 operator,lambda 会更复杂
product_lambda = reduce(lambda x, y: x * y, numbers)
print(product_lambda)  # 输出同样是 120,但 operator 更清晰

在自定义排序中作为 key 函数

假设我们有一个元组列表,我们想根据每个元组的第一个元素乘以 2 后的值来排序。

import operator
data = [(1, 'a'), (3, 'b'), (2, 'c')]
# sorted(iterable, key=function)
# 我们想用 (元素 * 2) 作为排序的 key
sorted_data = sorted(data, key=lambda item: operator.multiply(item[0], 2))
print(sorted_data)
# 输出: [(1, 'a'), (2, 'c'), (3, 'b')]
# 解释:排序依据是 1*2=2, 3*2=6, 2*2=4,所以顺序是 2, 4, 6。

numpy.multiply (来自 NumPy 库)

如果你在进行科学计算、数据分析或处理大型多维数组,那么你遇到的 multiply 几乎可以肯定是 numpy.multiply

它的作用是在两个 NumPy 数组之间进行元素级(element-wise)的乘法

什么是元素级乘法?

这意味着,新数组的每个元素都是原数组对应位置元素的乘积,这与线性代数中的矩阵乘法是不同的。

示例

基本元素级乘法

import numpy as np
# 创建两个数组
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
# 使用 np.multiply 进行元素级乘法
# 结果是 [1*10, 2*20, 3*30, 4*40]
c = np.multiply(a, b)
print(c)
# 输出: [ 10  40  90 160]
# 这和直接使用 * 运算符在 NumPy 中的效果是一样的
c_operator = a * b
print(c_operator)
# 输出: [ 10  40  90 160]

与矩阵乘法的区别

这是新手最容易混淆的地方,矩阵乘法在 NumPy 中使用 运算符或 np.dot() 函数。

import numpy as np
# 创建两个 2x2 的矩阵
A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])
# 1. 元素级乘法 (np.multiply 或 *)
element_wise_product = A * B
# 等价于 np.multiply(A, B)
print("元素级乘法 (A * B):")
print(element_wise_product)
"""
输出:
[[ 5 12]
 [21 32]]
解释: [[1*5, 2*6], [3*7, 4*8]]
"""
# 2. 矩阵乘法 (np.dot 或 @)
matrix_product = A @ B
# 等价于 np.dot(A, B)
print("\n矩阵乘法 (A @ B):")
print(matrix_product)
"""
输出:
[[19 22]
 [43 50]]
解释: 第一行第一列 = (1*5 + 2*7) = 19
      第一行第二列 = (1*6 + 2*8) = 22
      ...
"""

广播

np.multiply 也支持 NumPy 的“广播”机制,即不同形状的数组可以进行运算。

import numpy as np
# 一个 3x2 的矩阵
a = np.array([[1, 2],
              [3, 4],
              [5, 6]])
# 一个标量 (可以看作一个 1x1 的数组)
scalar = 10
# 矩阵中的每个元素都与标量相乘
result = np.multiply(a, scalar)
print(result)
"""
输出:
[[10 20]
 [30 40]
 [50 60]]
"""

特性 operator.multiply numpy.multiply
来源 Python 标准库 operator 第三方科学计算库 NumPy
作用 返回一个执行乘法运算的函数 对 NumPy 数组进行元素级乘法
使用场景 高阶函数(map, reduce)、动态操作、代码可读性 科学计算、数据分析、处理大型多维数组
示例 reduce(operator.multiply, [1,2,3]) -> 6 np.array([1,2]) * np.array([3,4]) -> [3, 8]
核心区别 获取乘法操作本身 在数组上执行乘法运算

当你下次看到 multiply 时,先想一想你是在写普通的 Python 代码(可能是 operator.multiply),还是在做数据分析(几乎肯定是 numpy.multiply)。

分享:
扫描分享到社交APP
上一篇
下一篇