是否可以添加具有列表理解的 where 子句?

2024-01-31

考虑以下列表理解

[ (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化和可读?


Update

即将在 python 3.8 中推出!PEP https://www.python.org/dev/peps/pep-0572/#syntax-and-semantics

# 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 次。

This for建造:

for y in [f(x)]

模仿where子句。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以添加具有列表理解的 where 子句? 的相关文章

随机推荐