赞
踩
在Python中的列表列表中获取所有对角线
我正在寻找一种Python的方式来获取(正方形)矩阵的所有对角线,以列表的形式表示。
假设我有以下矩阵:
matrix = [[-2, 5, 3, 2],
[ 9, -6, 5, 1],
[ 3, 2, 7, 3],
[-1, 8, -4, 8]]
然后,大对角线很容易:
l = len(matrix[0])
print [matrix[i][i] for i in range(l)] # [-2, -6, 7, 8]
print [matrix[l-1-i][i] for i in range(l-1,-1,-1)] # [ 2, 5, 2, -1]
但是我很难想出一种生成所有对角线的方法。 我正在寻找的输出是:
[[-2], [9, 5], [3,-6, 3], [-1, 2, 5, 2], [8, 7, 1], [-4, 3], [8],
[2], [3,1], [5, 5, 3], [-2, -6, 7, 8], [9, 2, -4], [3, 8], [-1]]
7个解决方案
50 votes
在numpy中可能有比下面更好的方法,但是我对它还不太熟悉:
import numpy as np
matrix = np.array(
[[-2, 5, 3, 2],
[ 9, -6, 5, 1],
[ 3, 2, 7, 3],
[-1, 8, -4, 8]])
diags = [matrix[::-1,:].diagonal(i) for i in range(-3,4)]
diags.extend(matrix.diagonal(i) for i in range(3,-4,-1))
print [n.tolist() for n in diags]
输出量
[[-2], [9, 5], [3, -6, 3], [-1, 2, 5, 2], [8, 7, 1], [-4, 3], [8], [2], [3, 1], [5, 5, 3], [-2, -6, 7, 8], [9, 2, -4], [3, 8], [-1]]
编辑:更新以针对任何矩阵大小进行概括。
import numpy as np
# Alter dimensions as needed
x,y = 3,4
# create a default array of specified dimensions
a = np.arange(x*y).reshape(x,y)
print a
# a.diagonal returns the top-left-to-lower-right diagonal "i"
# according to this diagram:
#
# 0 1 2 3 4 ...
# -1 0 1 2 3
# -2 -1 0 1 2
# -3 -2 -1 0 1
# :
#
# You wanted lower-left-to-upper-right and upper-left-to-lower-right diagonals.
#
# The syntax a[slice,slice] returns a new array with elements from the sliced ranges,
# where "slice" is Python's [start[:stop
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。