
本文介绍一种纯 python 实现方法,用于获取二维方阵或矩形矩阵上三角区域(严格上三角,即排除主对角线)中所有元素的行索引与列索引,无需依赖 numpy。
在实际开发中,有时受限于环境(如嵌入式场景、轻量级部署或依赖隔离要求),无法使用 NumPy 等科学计算库。此时若需提取矩阵上三角部分(不含主对角线)的索引对(如 (0,1), (0,2), (1,2)),可借助基础 Python 循环与列表操作高效完成。
以示例矩阵 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 为例,其严格上三角元素为 2(位置 (0,1))、3((0,2))、6((1,2)),目标正是生成对应的行索引列表 [0, 0, 1] 和列索引列表 [1, 2, 2]。
以下是推荐的实现方式:
def upper_triangle_indices(matrix):
"""
返回严格上三角区域(不含主对角线)的 (row, col) 索引列表
支持非方阵(按最小边截断,即只遍历 min(len(matrix), len(matrix[0])) 行)
"""
if not matrix or not matrix[0]:
return [], []
n_rows = len(matrix)
n_cols = len(matrix[0])
max_dim = min(n_rows, n_cols) # 确保不越界
row_indices = []
col_indices = []
for i in range(max_dim):
# 当前行 i,列索引从 i+1 开始,至该行末尾(或不超过 n_cols-1)
start_col = i + 1
end_col = min(n_cols, start_col + (n_cols - start_col)) # 实际取到 min(n_cols, n_cols)
# 更简洁写法:
for j in range(start_col, n_cols):
row_indices.append(i)
col_indices.append(j)
return row_indices, col_indices
# 示例使用
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rows, cols = upper_triangle_indices(matrix)
print("行索引:", rows) # [0, 0, 1]
print("列索引:", cols) # [1, 2, 2]
print("对应元素:", [matrix[i][j] for i, j in zip(rows, cols)]) # [2, 3, 6]✅ 关键说明:
- 该方法天然支持矩形矩阵(如 3×4 或 4×3),通过 min(n_rows, n_cols) 保证只处理有效上三角范围;
- 每次迭代中,第 i 行的列起始位置为 i+1,避免包含主对角线(i,i);
- 返回两个独立列表(row_indices, col_indices),便于后续与 zip() 配合构造坐标元组,或直接用于索引其他同构数据结构。
⚠️ 注意事项:
- 输入矩阵需为非空二维列表,且每行长度一致(即“类矩阵”结构);若存在不规则嵌套,建议先校验 all(len(row) == len(matrix[0]) for row in matrix);
- 若需兼容更通用场景(如返回元组列表 [(0,1), (0,2), (1,2)]),可改用 return list(zip(row_indices, col_indices));
- 时间复杂度为 O(n²),空间复杂度为 O(k)(k 为上三角元素个数),符合预期。
该方案简洁、可读性强,且完全脱离外部依赖,是 NumPy np.triu_indices 的轻量级替代方案。







