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

如何不使用for循环将一维NumPy数组转换为指定形式下三角矩阵

NumPy 无循环构造指定下三角矩阵实现方案

推荐方案(兼容性好、逻辑直观)

直接利用NumPy的广播机制构造索引映射,全程无显式for循环,向量化运算执行效率高,兼容所有主流NumPy版本。
完整代码如下:

import numpy as np

# 原始输入数组
arr = np.array([1, 2, 3, 4])
n = arr.size
# 构造行列索引网格
row_idx, col_idx = np.ogrid[:n, :n]
# 下三角区域取原数组对应位置值,上三角填0
result = np.where(
    row_idx >= col_idx,
    arr[n - 1 - (row_idx - col_idx)],
    0
)

执行后得到的result完全匹配目标输出:

array([[4, 0, 0, 0],
       [3, 4, 0, 0],
       [2, 3, 4, 0],
       [1, 2, 3, 4]])

可选方案(代码更简洁,适合高版本NumPy)

如果你使用的是NumPy 1.20.0及以上版本,可以用内置的滑动窗口视图函数实现,代码更短:

import numpy as np
from numpy.lib.stride_tricks import sliding_window_view

arr = np.array([1, 2, 3, 4])
n = arr.size
# 反转原数组后在前部补n-1个0
padded_arr = np.pad(arr[::-1], (n-1, 0), mode="constant")
# 取长度为n的滑动窗口后逐行反转得到结果
result = sliding_window_view(padded_arr, n)[:, ::-1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 06:31:10