问题:
def detect_monitors_and_modes(preferred_order, binp):
out = run_xrandr(binp)
findit = partial(get_mon_mode, preferred_order)
print 'OUTPUT', '\n'.join(out)
lst = map(findit, out)
print 'lst', lst
matches = filter(lambda x: x, lst)
print 'matches', matches
OUTPUT Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192
LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
1366x768 60.1*+ 40.1
1360x768 59.8 60.0
1024x768 60.0
800x600 60.3 56.2
640x480 59.9
VGA1 disconnected (normal left inverted right x axis y axis)
HDMI1 disconnected (normal left inverted right x axis y axis)
DP1 disconnected (normal left inverted right x axis y axis)
lst [None, 'LVDS1', '1366x768', None, None, None, None, None, None, None, None]
matches ['LVDS1', '1366x768']
具体来说,我想知道是否有更短/更惯用的方法来做到这一点:
lst = map(findit, out)
matches = filter(lambda x: x, lst)
显然,我不能仅使用filter
bc这将返回整行(LVDS1 connected 1366x768+0+0 (normal...
)而不是findit
返回的值。 map
会为不匹配的行返回None
。
(reduce
这里有用吗?但因为它不是犹太人......)
编辑:我想过滤掉这里的“假”值,即空字符串,None
s,False
等等,只留下findit
找到的积极匹配。
答案 0 :(得分:3)
我想在这里过滤掉“假的”值,即空字符串,Nones,False等等,只留下findit找到的正匹配值。
您可以简化为:
matches = filter(None, map(findit, out))
根据文档:
如果 function 为
None
,则假定为identity函数,即 iterable 的所有false元素都将被删除。
供参考:
答案 1 :(得分:1)
是的,使用列表推导
matches = [findit(x) for x in out if findit(x) is not None]
这是按照PEP所描述的“pythonic”方式进行的