Home > Software engineering >  how to split an array homogene in half of size by taking the triagle?
how to split an array homogene in half of size by taking the triagle?

Time:12-14

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

CodePudding user response:

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:])]

CodePudding user response:

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
  • Related