Retrieving values ​​from a list using an array with boolean expressions

I have a list of tuples like this:

listOfTuples = [(0, 1), (0, 2), (3, 1)]

and an array that might look like this:

myArray = np.array([-2, 9, 5])

In addition, I have an array with Boolean expressions, which I created as follows:

dummyArray = np.array([0, 1, 0.6])
myBooleanArray =  dummyArray < 1

myBooleanArray as follows:

array([True, False, True], dtype=bool)

Now I would like to extract values ​​from listOfTuplesand myArraybased on myBooleanArray. For myArraythis is straightforward, and I can just use:

myArray[myBooleanArray]

which gives me the desired exit

[-2  5]

However, when I use

listOfTuples[myBooleanArray]

I get

TypeError: only whole arrays with one element can be converted to Index

The workaround was to first convert this list to an array:

np.array(listOfTuples)[myBooleanArray]

what gives

[[0 1]
 [3 1]]

Is there a smarter way to do this? My desired result would be

[(0, 1), (3, 1)]
+4
source
2

, python, itertools.compress

>>> from itertools import compress
>>> list(compress(listOfTuples,bool_array))
[(0, 1), (3, 1)]

compress , , . .

, . :

for item in compress(listOfTuples,bool_array):
     #do stuff
+4

Kasra ,

In [30]: [i[0] for i in list(zip(listOfTuples,bools)) if i[1] == True ]
Out[30]: [(0, 1), (3, 1)]
+2

All Articles