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

标签 python python-3.x list-comprehension python-assignment-expression python-3.8

考虑以下列表理解

[ (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/

相关文章:

python - 在列表理解中使用 break

python - SQLAlchemy 查询 - 它们什么时候执行?

python - 正则表达式 - 删除两个标点符号之间的空格,但不删除标点符号和字母之间的空格

python - 如何使用以任何大写字母开头的正则表达式从 Pandas 系列中提取字符串

python - 在Python中使用一个列表理解来反转和反转二进制矩阵

javascript - 在 html 中加载 .js 文件

list - haskell中的质因数分解

python - 在文本文件中查找一个点并在 Python 中向该文件添加一个换行符?

python - 当我只调用一个方法时,为什么我的所有方法都在 python 中执行

list - Haskell-循环列表的每个第二个元素