Python生成器是否有`let`或`as`关键字? - python

我从Clojure进入Python,想知道是否有一种方法可以在生成器中包含“临时变量”。

在Clojure中,我可以在for生成器中使用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结果:

fnames = ["abc1234", "abcdef", "1024"]
matches = [re.match('(\w+?)(\d+)', fname) for fname in fnames]
matches = [match.groups() for match in matches if match is not None]
# [('abc', '1234'), ('1', '024')]

那么,有没有办法做下面的事情?如果没有,最Python化的方法是什么?

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

python大神给出的解决方案

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

[name for name in iterable if condition]

其中if condition部分是可选的。这就是grammar提供的全部内容。

但是,在您的特定情况下,可以在列表推导中放入generator expression:

matches = [m.groups() for m in (re.match('(\w+?)(\d+)', f) for f in fnames) if m]

演示:

>>> 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(错误值)。