首页 > 解决方案 > The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() with index function

问题描述

Well, in my Python code I'm trying to print out the index of a list of lists using a list, this way:

print(datos.tolist().index(lista_muestra_pequena[1]))

'datos' and 'lista_muestra_pequena' are two lists of lists, and I want to know which index have lista_muestra_pequena[1] in 'datos'. 'datos' is actually a numpy array, that's why I put .tolist()

One error give me Python when executing, this one: print(datos.tolist().index(lista_muestra_pequena[1]))

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand the function 'a.all()', used for arrays to specify if all elements of the array must satisfy the condition, or only one in 'a.any()' case. However, I don't understand why is telling me this on this case. I tried putting 'np.all()' in two sites on the line, but I don't get it.

标签: pythonarrays

解决方案


.index()方法不适用于数组作为参数(假设lista_muestra_pequena是一个数组)。

要获取datoswherelista_muestra_pequena[1]的索引,您可以使用numpy.where()方法:

print(np.where(datos == lista_muestra_pequena[1])[0][0]) # first occurrence

推荐阅读