You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现类似Mathematica的通用函数外积?

复刻Mathematica的通用外积功能

当然可以在Python中实现类似Mathematica的通用外积功能,下面提供两种实用方案:

方案一:列表推导式(无依赖)

这是最直接的实现方式,完全匹配Mathematica返回的嵌套列表结构:

def outer(func, lst1, lst2):
    return [[func(x, y) for y in lst2] for x in lst1]

示例用法

def f(a, b):
    return f"f({a}, {b})"

# 调用函数
result = outer(f, ['a', 'b'], ['x', 'y'])
# 输出:[['f(a, x)', 'f(a, y)'], ['f(b, x)', 'f(b, y)']]

方案二:NumPy实现(适合数值计算)

如果处理的是数值数组,想要利用向量化提升性能,可以用np.meshgrid生成元素对的二维网格,再应用自定义函数:

import numpy as np

def np_outer(func, arr1, arr2):
    arr1 = np.asarray(arr1)
    arr2 = np.asarray(arr2)
    # 使用'ij'索引确保结果维度顺序和Mathematica一致
    X, Y = np.meshgrid(arr1, arr2, indexing='ij')
    return func(X, Y)

数值函数示例

def add(a, b):
    return a + b

result = np_outer(add, [1, 2], [3, 4])
# 输出:
# array([[4, 5],
#        [5, 6]])

非向量化函数适配

如果你的函数仅支持标量输入,用np.vectorize包装后即可适配:

def scalar_func(a, b):
    return f"和为:{a + b}"

vectorized_func = np.vectorize(scalar_func)
result = np_outer(vectorized_func, [1, 2], [3, 4])
# 输出:
# array([['和为:4', '和为:5'],
#        ['和为:5', '和为:6']], dtype='<U6')

两种方案都能完全复刻Mathematica中Outer函数的核心逻辑:将二元函数应用于两个输入序列的所有元素对,生成二维结果结构。

内容的提问来源于stack exchange,提问作者Wintermute

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:20:32