Python:优雅而有效的屏蔽列表的方法 [英] Python: Elegant and efficient ways to mask a list
问题描述
示例:
from __future__ 导入师将 numpy 导入为 npn = 8"""屏蔽列表"""lst = 范围(n)打印列表# 掩码(过滤器)msk = [(el>3) and (el<=6) for el in lst]打印 msk# 面膜的使用打印 [lst[i] for i in xrange(len(lst)) 如果 msk[i]]"""屏蔽数组"""ary = np.arange(n)印刷厂# 掩码(过滤器)msk = (ary>3)&(ary<=6)打印 msk# 面膜的使用print ary[msk] # 非常优雅
结果是:
<预><代码>>>>[0, 1, 2, 3, 4, 5, 6, 7][假,假,假,假,真,真,真,假][4, 5, 6][0 1 2 3 4 5 6 7]【假假假假真假真假】[4 5 6]如您所见,与列表相比,对数组进行掩码的操作更加优雅.如果您尝试使用列表中的数组屏蔽方案,您将收到一个错误:
<预><代码>>>>lst[msk]回溯(最近一次调用最后一次):文件<交互式输入>",第 1 行,在 <module> 中类型错误:只有一个元素的整数数组才能转换为索引问题是为 list
找到一个优雅的掩码.
更新:jamylak
的回答因引入 compress
而被接受,但是 Joel Cornett
提到的要点使解决方案完全符合我的兴趣.
如果你使用的是 numpy
:
如果您不使用 numpy,您正在寻找 itertools.compress
Example:
from __future__ import division
import numpy as np
n = 8
"""masking lists"""
lst = range(n)
print lst
# the mask (filter)
msk = [(el>3) and (el<=6) for el in lst]
print msk
# use of the mask
print [lst[i] for i in xrange(len(lst)) if msk[i]]
"""masking arrays"""
ary = np.arange(n)
print ary
# the mask (filter)
msk = (ary>3)&(ary<=6)
print msk
# use of the mask
print ary[msk] # very elegant
and the results are:
>>>
[0, 1, 2, 3, 4, 5, 6, 7]
[False, False, False, False, True, True, True, False]
[4, 5, 6]
[0 1 2 3 4 5 6 7]
[False False False False True True True False]
[4 5 6]
As you see the operation of masking on array is more elegant compared to list. If you try to use the array masking scheme on list you'll get an error:
>>> lst[msk]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: only integer arrays with one element can be converted to an index
The question is to find an elegant masking for list
s.
Updates:
The answer by jamylak
was accepted for introducing compress
however the points mentioned by Joel Cornett
made the solution complete to a desired form of my interest.
>>> mlist = MaskableList
>>> mlist(lst)[msk]
>>> [4, 5, 6]
If you are using numpy
:
>>> import numpy as np
>>> a = np.arange(8)
>>> mask = np.array([False, False, False, False, True, True, True, False], dtype=np.bool)
>>> a[mask]
array([4, 5, 6])
If you are not using numpy you are looking for itertools.compress
>>> from itertools import compress
>>> a = range(8)
>>> mask = [False, False, False, False, True, True, True, False]
>>> list(compress(a, mask))
[4, 5, 6]
这篇关于Python:优雅而有效的屏蔽列表的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!