使用具有布尔表达式的数组从列表中提取值 [英] Extract 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 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
因此看起来像这样:
array([True, False, True], dtype=bool)
现在,我想基于myBooleanArray
从listOfTuples
和myArray
中提取值.对于myArray
,它很简单,我可以使用:
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]
这给了我想要的输出
[-2 5]
但是,当我使用
listOfTuples[myBooleanArray]
我收到
TypeError:只有具有一个元素的整数数组可以转换为 索引
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]
产生
[[0 1]
[3 1]]
有没有更聪明的方法?我想要的输出将是
Is there any smarter way of doing this? My desired output would be
[(0, 1), (3, 1)]
推荐答案
您已经做了最好的方法,但是如果您正在寻找python解决方案,则可以使用itertools.compress
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)]
compress
的优点之一是,如果列表很大,它会返回生成器,并且效率很高.因为使用生成器可以节省很多内存.
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
这篇关于使用具有布尔表达式的数组从列表中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!