简体   繁体   中英

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. I am looking to have this new list have the values 1, 2, 3, 4, 5, 7 instead. 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.

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. 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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