这是生成器表达式吗?

2024-04-24 10:11:32 发布

您现在位置:Python中文网/ 问答频道 /正文

几天前我问了一个关于列表理解的问题:Elegant way to delete items in a list which do not has substrings that appear in another list

不管怎样,我的问题得到了很好的答案。它是一个列表:

[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部分。在我看来,它像一个生成器表达式,但我不确定。我认为最好在另一个帖子里问这个问题。你知道吗

那么它是一个生成器表达式还是别的什么?你知道吗


Tags: toinwhich列表for表达式notitems
2条回答

让python告诉您它是什么:

>>> p=[]
>>> exclude_list=[]
>>> type(e not in p for e in exclude_list)
<class 'generator'>

是的,all(e not in p for e in exclude_list)是一个包含生成器表达式的调用。传递给调用的only参数的生成器表达式可以省略括号。在这里,这就是被调用的^{} function。你知道吗

Generator expressions reference documentation

The parentheses can be omitted on calls with only one argument.

all()函数(以及伴随函数^{})通常被赋予一个生成器表达式,因为这允许对一系列测试进行延迟评估。只执行足够的e not in p测试来确定结果;如果有任何^{e not in p测试为false,则all()会提前返回,并且不会执行进一步的测试。你知道吗

相关问题 更多 >