python - 以 Python 方式整理列表推导式

标签 python

像 Haskell 这样的 FP 可以简单地绑定(bind)一个 (var) 名称,例如:

[(g y, h y) | x <- mylist, let y = f x]

Python 可能会在下面实现:

mylist = [f(x) for x in mylist]
mylist = [(g(y), h(y)) for y in mylist]

Python 3.8 中的海象赋值似乎是对 simplify list comprehensions 的破解:

[(y := f(x), g(y), h(y)) for x in mylist]

在这种情况下,到目前为止被认为是Pythonic的方式是什么?

最佳答案

海象运算符创建二元组的正确用法是

mylist = [(g(y:=f(x)), h(y)) for x in mylist]

是的,这比三元组版本更可怕。如果您想放弃海象运算符,请使用 := 应该消除的版本:

mylist = [(g(y), h(y)) for x in mylist for y in [f(x)]]

或者更简单

mylist = [(g(y), h(y)) for y in map(f, mylist)]

我不会说海象操作符总是如此笨拙,但它似乎比它值得的麻烦更多。

关于python - 以 Python 方式整理列表推导式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59001336/

相关文章:

python - Django 的 CachedStaticFilesStorage 不散列文件 url

python - 使用pygame中的按钮调整文本大小

python - 两个基数中的回文数,欧拉计划 #36

python - django 管理 url 重定向到自定义 url

python - 为什么我得到 "Error while validating constraint None"?

python - Python 列表操作的性能问题

python - 从 Pandas Condition 获取行号和列号

Python:将参数传递给函数

python - 在 Python 中减少 for 循环是不可能的?

python - Raspberry Pi 3 属性报错sslerror报错