python - 使用理解而不是 for 循环

标签 python list-comprehension

以下是我的代码的简化示例。

>>> def action(num):
        print "Number is", num
>>> items = [1, 3, 6]
>>> for i in [j for j in items if j > 4]:
        action(i)
Number is 6

我的问题如下:for 循环简单地替换为仍会调用 Action 功能?即:

>>> (action(j) for j in items if j > 2)
Number is 6

最佳答案

这根本不应该使用生成器或理解。

def action(num):
    print "Number is", num

items = [1, 3, 6]
for j in items:
    if j > 4:
        action(i)

生成器延迟计算。表达式 (action(j) for j in items if j > 2) 只会将生成器表达式返回给调用者。除非你明确地用尽它,否则它不会发生任何事情。列表理解急切地求值,但是,在这种特殊情况下,您会得到一个毫无意义的 list。只需使用常规循环即可。

关于python - 使用理解而不是 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38809247/

相关文章:

python - 我应该如何使用列表理解重写这个 map() 示例?

python - 测试值是否存在于多个列表中

python - pygame中物体的速度?

python - Django/Wagtail 一些图片上传错误500

python - 在 Python 中并行化列表理解

python - 如何将以下嵌套的 dict 列表解压缩为元组?

python - 在 Python : is there something like -0? 中对列表进行切片

python - 有没有一种方法可以在 python 的 argparse 中创建参数,如果没有给出值则返回 true

python - Azure功能不使用可用主机实例

python - XGBOOST 特征名称错误 - Python