python - python列表理解中的haskell的 "where"

标签 python

如果 lst 是一个整数列表,我想要

[dif for i in range(1, len(lst)) where dif = lst[i]-lst[i-1] if dif < 5]

但显然,像这样绑定(bind)一个变量在语法上是不正确的(除了 where 是从 Haskell 借来的)。 我能行

[dif for i in range(1, len(lst)) for dif in (lst[i]-lst[i-1],) if dif < 5]

使 dif 在长度为一的可迭代中运行。另一种选择:

[lst[i]-lst[i-1] for i in range(1, len(lst)) if lst[i]-lst[i-1] < 5]

此外,我可以定义一个具有差异的中间列表,然后对其进行过滤。但是这两种选择都不是很好。有没有好的单线能得到我想要的?

最佳答案

我认为这里没有出色的 1-liner。我想既然它是一个列表,你可以使用切片:

[a-b for a, b in zip(lst[1:], lst) if a-b < 5]

这不是效率的,因为 lst[1:] 创建了一个副本并且 zip 也具体化了一个新列表(在 python2 。X)。我们可以使用 itertools 做得更好:

from itertools import izip, islice
[a-b for a, b in izip(islice(lst, 1), lst) if a-b < 5]

(注意 python3.x 取消了 izip,所以如果您使用 python3,只需使用 zip)。

关于python - python列表理解中的haskell的 "where",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682382/

相关文章:

Python RQ 属性错误 : 'dict' object has no attribute '__module__'

python - pandas DataFrame 中的内存处理

python - 多线程修改python中的全局列表

python - yfinance "history"函数在我的 python session 中不起作用,我该如何调试它?

python - 在中间暂停/恢复 python 脚本

python - 如何将图像移动到不同的目录?

python - Scrapy - 提交带有多个按钮的表单

python - 使用python-keycloak登录keycloak后如何获取 token

缓冲区中的 Python Windows API 转储过程然后进行 REGEX 搜索

python - 从线程目标访问 `self`