TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index

前端 未结 2 1698
谎友^
谎友^ 2021-01-18 11:39

The following code:

x = list(range(0,10))
random.shuffle(x)
ind = np.argsort(x)
x[ind]

produces the error: TypeError: only integer scalar a

2条回答
  •  余生分开走
    2021-01-18 11:47

    Good answer - but I would add that if the list cannot be converted to a numpy array (i.e. you have a list of string) you cannot slice it with an array of indices as described above. The most straightforward alternative is

    [x[i] for i in ind]

提交回复
热议问题