Home > Software engineering >  TypeError: list indices must be integers or slices, not list (Python)
TypeError: list indices must be integers or slices, not list (Python)

Time:07-30

I have a list Ii0 containing numpy arrays with different shapes. I want to reorganize these arrays based on increasing j. But I get an error. I present the expected output.

import numpy as np
Ii0 = [np.array([[0, 1],[0, 2],[1, 3],[2, 4],[4,3]]),
       np.array([[0, 1],[0, 2],[1, 3],[2, 5],[4,3],[3,4]])]

order = [k[:,1].argsort() for k in Ii0]
print(order)
Ii01 =Ii0[order]
print("Ii01 =",[Ii01])

The error is

in <module>
    Ii01 =Ii0[order]

TypeError: list indices must be integers or slices, not list

The expected output is

[array([[0, 1],[0, 2],[1, 3],[4,3],[2, 4]]),
 array([[0, 1],[0, 2],[1, 3],[4,3],[3,4],[2, 5]])]

CodePudding user response:

i hope it'll helps you

import numpy as np
Ii0 = [np.array([[0, 1],[0, 2],[1, 3],[2, 4],[4,3]]),
       np.array([[0, 1],[0, 2],[1, 3],[2, 5],[4,3],[3,4]])]

Ii01 = [i[i[:,1].argsort()] for i in Ii0]
print("Ii01 =",Ii01)

>> Ii01 = [array([[0, 1],[0, 2],[1, 3],[4, 3],[2, 4]]), array([[0, 1],[0, 2],[1, 3],[4, 3],[3, 4],[2, 5]])]
  • Related