Extract values from a list using an array with boolean expressions

混江龙づ霸主 提交于 2020-01-03 15:58:03

问题


I have a list of tuples like this:

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

and an array that could look like this:

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

Furthermore, I have an array with Boolean expressions which I created like this:

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

myBooleanArray therefore looks like this:

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

Now I would like to extract values from listOfTuples and myArray based on myBooleanArray. For myArray it is straight forward and I can just use:

myArray[myBooleanArray]

which gives me the desired output

[-2  5]

However, when I use

listOfTuples[myBooleanArray]

I receive

TypeError: only integer arrays with one element can be converted to an index

A workaround would be to convert this list to an array first by doing:

np.array(listOfTuples)[myBooleanArray]

which yields

[[0 1]
 [3 1]]

Is there any smarter way of doing this? My desired output would be

[(0, 1), (3, 1)]

回答1:


Already you have done the best way,but if you are looking for a python solution you can use itertools.compress

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

One of the advantage of compress is that it returns a generator and its very efficient if you have huge list. because you'll save much memory with using generators.

And if you want to loop over the result you don't need convert to list. You can just do :

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



回答2:


The answer by Kasra is the best this is just an alternate

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


来源:https://stackoverflow.com/questions/30624340/extract-values-from-a-list-using-an-array-with-boolean-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!