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

如何用SymPy的TensorProduct批量计算多矩阵的张量积?

解决SymPy TensorProduct传入列表/元组的问题

直接用Python的参数解包语法就能解决这个问题,具体做法是在列表或元组前加*,把容器里的元素逐个传给TensorProduct函数,和直接写多个参数的效果完全一致。

举个实际例子:

from sympy import Matrix, TensorProduct

# 定义测试矩阵
m1 = Matrix([[1, 0], [0, 1]])
m2 = Matrix([[2, 3], [4, 5]])
m3 = Matrix([[6, 7], [8, 9]])

# 将矩阵存入列表
matrices = [m1, m2, m3]

# 用*解包列表传入TensorProduct
result = TensorProduct(*matrices)
print(result)

如果是元组,用法完全相同:

matrices_tuple = (m1, m2, m3)
result = TensorProduct(*matrices_tuple)

TensorProduct本身支持接收多个位置参数,*操作符的作用是把可迭代对象(列表、元组等)中的元素依次展开为函数的位置参数,和直接写TensorProduct(m1, m2, m3)的调用逻辑完全一致,不需要额外找替代函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:57:35