Determining if a list contains a specific numpy array

import numpy as np a = np.eye(2) b = np.array([1,1],[0,1]) my_list = [a, b] 

a in my_list returns true , but b in my_list returns a ValueError: the truth value of an array with more than one element is ambiguous. Use a.any () or a.all () ". I can get around this by first converting arrays to strings or lists, but is there a nicer (more Pythonic) way to do this?

+4
source share
2 answers

The problem is that in numpy, the == operator returns an array:

 >>> a == b array([[ True, False], [ True, True]], dtype=bool) 

You use .array_equal() to compare arrays with a purely boolean value.

 >>> any(np.array_equal(a, x) for x in my_list) True >>> any(np.array_equal(b, x) for x in my_list) True >>> any(np.array_equal(np.array([a, a]), x) for x in my_list) False >>> any(np.array_equal(np.array([[0,0],[0,0]]), x) for x in my_list) False 
+3
source

More about the problem. If you configure my_list with

 my_list = [b,a] 

one that fails is ... An interesting problem.

-one
source

Source: https://habr.com/ru/post/1491903/


All Articles