简体   繁体   English

从更大的2D数组中提取每个2D正方形子数组的对角线

[英]Extract diagonals of each 2D square sub-array from a larger 2D array

This is my first programming class and I'm very excited to learn Python for Data Science. 这是我的第一门编程课,我为学习Python for Data Science感到非常兴奋。 I cannot figure out how to write a loop that returns all diagonal numbers in the matrix. 我无法弄清楚如何编写一个返回矩阵中所有对角线数字的循环。 Below is the code, how close or far off am I? 下面是代码,我离我有多远? Thank you! 谢谢!

import numpy as np
cols = 0

matrixA = np.array([[2,0,0], [0,3,0], [0,0,4], [6,0,0], [0,7,0], [0,0,8]])

for rows in range(6):
    if rows == cols:
        print(matrixA[rows, cols])
    cols = cols + 1

Your current solution does not work because it does not take into account the fact that matrixA is not square. 您当前的解决方案不起作用,因为它没有考虑到matrixA不是正方形的事实。 You will have to take care that your indices do not run out of bounds. 您将必须确保索引不会超出范围。 Running it gives: 运行它可以得到:

IndexError: index 3 is out of bounds for axis 1 with size 3

This is because the maximum value that cols is allowed to take here is 2 . 这是因为cols允许在此处采用的最大值是2


As an alternative, you could use np.diag : 或者,您可以使用np.diag

print(x)
array([[2, 0, 0],
       [0, 3, 0],
       [0, 0, 4],
       [6, 0, 0],
       [0, 7, 0],
       [0, 0, 8]])

res = np.array([np.diag(x, -offset) for offset in range(0, *x.shape)])

print(res)
array([[2, 3, 4],
       [6, 7, 8]])

If you want a 1D result, call np.ravel : 如果想要一维结果,请调用np.ravel

print(res.ravel())
array([2, 3, 4, 6, 7, 8])

You don't need heavy library like numpy to achieve this simple task. 您不需要像numpy这样的繁重的库即可完成此简单任务。 In plain python you can do it via using zip and itertools.cycle(...) as: 在普通的python中,您可以通过使用zipitertools.cycle(...)为:

>>> from itertools import cycle

>>> my_list = [[2,0,0], [0,3,0], [0,0,4], [6,0,0], [0,7,0], [0,0,8]]
>>> for i, j in zip(my_list, cycle(range(3))):
...     print(i[j])
...
2
3
4
6
7
8

Why have cols at all? 为什么要有cols? It's always the same as rows, right? 总是和行一样吧?

for rows in range(6):
    print(matrixA[rows,rows])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM