python计算一个矩阵的主对角线_在Python中获取矩阵/列表列表中的所有对角线

在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

print

# 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[:step]] format.

# "::-1" returns the rows in reverse. ":" returns the columns as is,

# effectively vertically mirroring the original array so the wanted diagonals are

# lower-right-to-uppper-left.

#

# Then a list comprehension is used to collect all the diagonals. The range

# is -x+1 to y (exclusive of y), so for a matrix like the example above

# (x,y) = (4,5) = -3 to 4.

diags = [a[::-1,:].diagonal(i) for i in range(-a.shape[0]+1,a.shape[1])]

# Now back to the original array to get the upper-left-to-lower-right diagonals,

# starting from the right, so the range needed for shape (x,y) was y-1 to -x+1 descending.

diags.extend(a.diagonal(i) for i in range(a.shape[1]-1,-a.shape[0],-1))

# Another list comp to convert back to Python lists from numpy arrays,

# so it prints what you requested.

print [n.tolist() for n in diags]

输出[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

[[0], [4, 1], [8, 5, 2], [9, 6, 3], [10, 7], [11], [3], [2, 7], [1, 6, 11], [0, 5, 10], [4, 9], [8]]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值