每次我运行此代码时,它都说numpy.ndarray没有属性'index'



当我运行此代码时,它会返回numpy.ndarray对象没有属性。我正在尝试编写一个函数,以防万一给出的数字在数组中将返回以该数字在数组中的位置。

a = np.c_[np.array([1, 2, 3, 4, 5])]
x = int(input('Type a number'))
def findelement(x, a):
    if x in a:
        print (a.index(x))    
    else:
        print (-1)
print(findelement(x, a))

请使用np.where代替list.index

import numpy as np
a = np.c_[np.array([1, 2, 3, 4, 5])]
x = int(input('Type a number: '))
def findelement(x, a):
    if x in a:
        print(np.where(a == x)[0][0])    
    else:
        print(-1)
print(findelement(x, a))

结果:

Type a number: 3
2
None

注意np.where返回输入数组中元素的索引 满足给定的条件。

您应该检查np.wherenp.argwhere

最新更新