'any'不会引发错误?

问题描述:

我玩弄然后我注意到了这一点:'any'不会引发错误?

>>> l = input().split() 
1 25 11 4 
>>> any(s == s[::-1] for s in l) 
True 
>>> s == s[::-1] for s in l 
SyntaxError: invalid syntax 
>>> 

为什么any(s == s[::-1] for s in l)工作,如果s == s[::-1] for s in l本身会提高错误?

+1

请解释为什么我不应该问这个问题。 – micahwood50

+0

请将您的代码添加为文本,而不是图片。 – Matthias

+0

这是他们低估了我的原因吗?他们至少应该知道,他们可以编辑... – micahwood50

any(s == s[::-1] for s in l) 

相同:

any((s == s[::-1] for s in l)) 

和:

(s == s[::-1] for s in l) 

不是语法错误。这是一个生成器表达式。正如您发现括号是围绕生成器表达式所必需的,除非它们作为函数调用的唯一参数出现。

要完成丹D.答案,

(s == s[::-1] for s in l) 

是这样的:

def your_function(): 
    for s in l: 
     yield s == s[::-1]