简体   繁体   English

从矩阵python 2的右上角到左下角打印对角线

[英]Printing diagonal from top-right to bottom-left of matrix python 2

have a question regarding my code, and I'm really lost I need to create empty diagonal list outputting number from maxtrix from top-right ot bottom-left so it is [5, 9, 13, 17, 21]. 有一个关于我的代码的问题,我真的迷失了我需要从右上角左下角创建空对角线列表输出数字,所以它是[5,9,13,17,21]。

matrix = [[ 1,  2,  3,  4,  5],
          [ 6,  7,  8,  9, 10],
          [11, 12, 13, 14, 15],
          [16, 17, 18, 19, 20],
          [21, 22, 23, 24, 25]]

diagonal = []
for posi in matrix: 
    diagonal.append(posi[len(matrix)-1])

print diagonal

This is how far I got but it only outputs the last set of the numbers. 这是我得到了多远,但它只输出最后一组数字。

I can only change the value of 我只能改变它的价值

for posi in ##here##: 
    diagonal.append(##here## ##here##)

Options I have are: 我有的选择是:

matrix[posi]
matrix
range(len(matrix)-1)
posi
[len(matrix)-1]
[len(matrix)-1-posi)
posi
And like [4][0], [3][1], [1],[2]
[0,1,2,3,4]

It been trying to figure it out and lost now, any help is greatly appreciated Thank you 它一直试图弄清楚它现在丢失,任何帮助都非常感谢谢谢

If you have to use one of those options, I'd go with: 如果你必须使用其中一个选项,我会选择:

for posi in [0,1,2,3,4]: 
    diagonal.append(matrix[posi][len(matrix)-1-posi])

Perhaps, here is the simple solution with Enumerate 也许,这是Enumerate的简单解决方案

diagonal = []
for i, j in enumerate(matrix):
    diagonal.append(j[-(i+1)])

# or using list comprehension along with enumerate
diagonal = [j[-(i+1)] for i, j in enumerate(matrix)]

print diagonal

While the option being looked for is probably: 虽然正在寻找的选项可能是:

for posi in range(len(matrix)):
    diagonal.append(matrix[posi][len(matrix)-1-posi])

This isn't very pythonic and generally you would iterate over the matrix vs. indices and just use a negative index to count from the back, so a simple list comprehension: 这不是非常pythonic,通常你会迭代矩阵与索引,只是使用负索引从后面计数,所以一个简单的列表理解:

diagonal = [row[-posi] for posi, row in enumerate(matrix, 1)]
# [5, 9, 13, 17, 21]

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

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