Python生成器是否有'let'或'as'关键词?

2024-09-25 02:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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结果:

^{pr2}$

那么,有没有一种方法可以做到以下几点呢?如果不是,什么是最Python的方式?在

matches = [re.match('(\w+?)(\d+)', fname) as match 
   for fname in fnames
   if match is not None]

Tags: 方法renonefordefmatchgeneratorfname
1条回答
网友
1楼 · 发布于 2024-09-25 02:33:16

不,Clojure的let没有直接等价物。Python列表理解的基本结构是:

[name for name in iterable if condition]

其中if condition部分是可选的。这就是grammar提供的全部功能。在


但是,在您的特定情况下,您可以在列表理解中添加generator expression

^{pr2}$

演示:

>>> import re
>>> fnames = ["abc1234", "abcdef", "1024"]
>>> matches = [m.groups() for m in (re.match('(\w+?)(\d+)', f) for f in fnames) if m]
>>> matches
[('abc', '1234'), ('1', '024')]
>>>

另外,您会注意到我删除了您条件中的is not None部分。虽然显式测试None通常是个好主意,但在这种情况下不需要这样做,因为re.match总是返回匹配对象(一个真值)或None(错误值)。在

相关问题 更多 >