考虑以下列表理解
[ (x,f(x)) for x in iterable if f(x) ]
这会根据条件 f
过滤可迭代对象并返回成对的 x,f(x)
。这种方法的问题是 f(x)
被计算了两次。
如果我们能像这样写就太好了
[ (x,fx) for x in iterable if fx where fx = f(x) ]
or
[ (x,fx) for x in iterable if fx with f(x) as fx ]
但在 python 中,我们必须使用嵌套推导式来编写,以避免重复调用 f(x),这使得推导式看起来不太清晰
[ (x,fx) for x,fx in ( (y,f(y) for y in iterable ) if fx ]
有没有其他方法可以让它更具 Python 风格和可读性?
更新
即将在 python 3.8 中推出! PEP
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
最佳答案
没有 where
语句,但您可以使用 for
“模拟”它:
a=[0]
def f(x):
a[0] += 1
return 2*x
print [ (x, y) for x in range(5) for y in [f(x)] if y != 2 ]
print "The function was executed %s times" % a[0]
执行:
$ python 2.py
[(0, 0), (2, 4), (3, 6), (4, 8)]
The function was executed 5 times
如您所见,函数执行了 5 次,而不是 10 次或 9 次。
这个for
构造:
for y in [f(x)]
模仿where子句。
关于python - 是否可以添加带有列表理解的 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11608238/