本文介绍了Python的:优雅和高效的方法来掩盖列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
从__future__进口部
导入numpy的是NPN = 8
屏蔽列表
LST =范围(N)
打印LST#面具(过滤器)
MSK = [(报→3)和(埃尔&下; = 6),用于EL在LST]
打印MSK#使用面膜
打印[LST [I]因我的xrange(LEN(LST))如果MSK [I]掩蔽阵列
元= np.arange(N)
打印元#面具(过滤器)
MSK =(进制→3)及(进制&下; = 6)
打印MSK#使用面膜
打印元[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号线,上述<&模块GT;
类型错误:只有整数阵列,一个元件可以被转换为一个索引
问题是要找到列表
秒。优雅的屏蔽
更新:结果
通过 jamylak
答案被接纳为引进 COM preSS
但是通过提到的几点乔尔·科尼特
提出的解决方案,完整的我关心的期望形式。
>>> mlist = MaskableList
>>> mlist(LST)[MSK]
>>> [4,5,6]
解决方案
您正在寻找的
从文档实例
等同于:
高清COM preSS(数据选择器):
COM#preSS('ABCDEF',[1,0,1,0,1,1]) - GT; A C电子网
回报(D为D,S在izip(数据选择器)如果s)
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]
解决方案
You are looking for itertools.compress
Example from the docs
Equivalent to:
def compress(data, selectors):
# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
return (d for d, s in izip(data, selectors) if s)
这篇关于Python的:优雅和高效的方法来掩盖列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!