这是生成器表达式吗?
Is this a generator expression?
几天前我问了一个关于列表理解的问题:
无论如何,我的问题得到了很好的回答。这是一个列表理解:
[p for p in process_list if all(e not in p for e in exclude_list)]
我明白了这个想法并将其应用到我的工作中。但我不确定 e not in p for e in exclude_list
部分是否正确。对我来说它看起来像一个生成器表达式,但我不确定。我觉得这个问题最好在另一个 post.
中问
那么它是生成器表达式还是其他东西?
是的,all(e not in p for e in exclude_list)
是包含生成器表达式的调用。作为传递给调用的 only 参数的生成器表达式可以省略括号。在这里,这就是被调用的 all()
function。
来自Generator expressions reference documentation:
The parentheses can be omitted on calls with only one argument.
all()
函数(以及伴随函数 any()
通常被赋予一个生成器表达式,因为这允许对一系列测试进行延迟评估。只够 e not in p
执行测试以确定结果;如果有 any e not in p
测试为假,则提前 all()
returns 并且不会执行进一步的测试。
让python告诉你它是什么:
>>> p=[]
>>> exclude_list=[]
>>> type(e not in p for e in exclude_list)
<class 'generator'>
几天前我问了一个关于列表理解的问题:
无论如何,我的问题得到了很好的回答。这是一个列表理解:
[p for p in process_list if all(e not in p for e in exclude_list)]
我明白了这个想法并将其应用到我的工作中。但我不确定 e not in p for e in exclude_list
部分是否正确。对我来说它看起来像一个生成器表达式,但我不确定。我觉得这个问题最好在另一个 post.
那么它是生成器表达式还是其他东西?
是的,all(e not in p for e in exclude_list)
是包含生成器表达式的调用。作为传递给调用的 only 参数的生成器表达式可以省略括号。在这里,这就是被调用的 all()
function。
来自Generator expressions reference documentation:
The parentheses can be omitted on calls with only one argument.
all()
函数(以及伴随函数 any()
通常被赋予一个生成器表达式,因为这允许对一系列测试进行延迟评估。只够 e not in p
执行测试以确定结果;如果有 any e not in p
测试为假,则提前 all()
returns 并且不会执行进一步的测试。
让python告诉你它是什么:
>>> p=[]
>>> exclude_list=[]
>>> type(e not in p for e in exclude_list)
<class 'generator'>