how to split an array homogene in half of size by taking the triagle?

Question:

i have this array and i want to split it in the half how i can do it?

a = [[0., 15., 19., 18., 17.],
     [15., 0., 14., 12., 23.],
     [19., 14.,  0., 14., 21.],
     [18., 12., 14., 0., 14.],
     [17., 23., 21., 14.,  0.]]

how i can get this half size of this array:

[[0.],
    [15.,0],
    [19., 14.,0],
    [18., 12., 14.,0],
    [17., 23., 21., 14.,0]]
Asked By: Hi Chem

||

Answers:

You can do something like this :

half = [row[:i+1] for i, row in enumerate(a)]

If you do not want the diagonal, you can add [1:] :

half = [row[:i+1] for i, row in enumerate(a[1:])]
Answered By: charon25

Looking at your requirement you want to select

  • 0 items from the 0 index.
  • 1 item from the 1 index.
  • 2 items from the 2 index.
    and so on…
    So simply do this:
res = [a[i][:i+1] for i in range(len(a))]
print(res)

What did I do above?

  • Iterate over a and slice the values.
  • Index + 1 since you want to include the index
Answered By: The Myth
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.