我从Clojure来到Python,想知道是否有一种方法可以在生成器中使用“临时变量”。在
在Clojure中,我可以在for generator中使用let
来命名项上的中间计算:
(def fnames ["abc1234" "abcdef" "1024"])
(for [fname fnames
:let [matches (re-matches #"(\w+?)(\d+)" fname)]
:when matches]
matches)
;=> (["abc10" "abc" "1234"] ["1024" "1" "024"])
在Python中,我需要使用生成器两次来过滤None
结果:
那么,有没有一种方法可以做到以下几点呢?如果不是,什么是最Python的方式?在
matches = [re.match('(\w+?)(\d+)', fname) as match
for fname in fnames
if match is not None]
不,Clojure的
let
没有直接等价物。Python列表理解的基本结构是:其中
if condition
部分是可选的。这就是grammar提供的全部功能。在但是,在您的特定情况下,您可以在列表理解中添加generator expression:
^{pr2}$演示:
另外,您会注意到我删除了您条件中的
is not None
部分。虽然显式测试None
通常是个好主意,但在这种情况下不需要这样做,因为re.match
总是返回匹配对象(一个真值)或None
(错误值)。在相关问题 更多 >
编程相关推荐