简体   繁体   English

三角形的数组值 Python

[英]Array values in triangular shape Python

I am trying to take values from a given array in a right angle triangular shape.我正在尝试以直角三角形从给定数组中获取值。 I have tried following code:我试过以下代码:

matrix =     [[1,2,3],
          [4,5,6],
          [7,8,9],
          [10,11,12]]

row = 3
col =3

new = []

for i in range(0, row):

    for j in range(0, col):

        if (i > j):

            print("", end=" ")

        else:
            new.append(new[i][j])

                 end=" ")
print(new)

However this makes the new list 'new' have the values 1, 2, 3, 5, 6, 9. So the triangle is going to the right side of the array.然而,这使得新列表“新”具有值 1、2、3、5、6、9。因此三角形将移至数组的右侧。 I am looking to have this new list have the values 1, 2, 3, 4, 5, 7 instead.我希望这个新列表的值改为 1、2、3、4、5、7。 I know the issue is with the 2nd for loop but I have tried experimenting with the code and haven't been able to get it quite right.我知道问题出在第二个 for 循环上,但我尝试过使用代码进行试验,但未能完全正确。

You can do the following:您可以执行以下操作:

>>> [row[:i] for row, i in zip(matrix, range(3, 0, -1))]
[[1, 2, 3], [4, 5], [7]]

This takes decreasing slices of the rows in the matrix by zipping the matrix with a range of appropriate stop indeces.这通过使用适当的停止索引range zipping矩阵来减少矩阵中的行切片。 And if you want a flat list, you can nest the comprehension:如果你想要一个平面列表,你可以嵌套理解:

>>> [x for row, i in zip(matrix, range(3, 0, -1)) for x in row[:i]]
[1, 2, 3, 4, 5, 7]

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

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