python - 为什么以下 Python 生成器表达式可以工作?

标签 python generator-expression

我正在尝试理解我在野外遇到的常见生成器习惯用法。我注意到它(并使用它)很长时间了,但从未费心去质疑它。使用玩具函数的习惯用法示例:

def contains_vowels(string):
    vowels = set('aeiou')

    if any((char in vowels) for char in string):
        return True

    return False

为什么any((元音中的字符) for 字符串中的字符) 按预期工作?我知道 (char in momels) 是一个生成器表达式,但是例如(元音中的字符) for 字符串中的字符 不是函数调用之外的有效生成器。

换句话说,既然上面的代码是有效的,为什么下面的代码不起作用:

    for b in (char in vowels) for char in string:
        print b

(显然,使整个表达式成为生成器确实按预期工作:

    for b in (char in vowels for char in string):
        print b

)

我知道这是一个有点愚蠢的问题,但答案对我来说并不是立即直观的。这只是“因为这就是语法的工作方式”的情况,还是我遗漏了什么?

最佳答案

I get that (char in vowels) is a generator expression,

事实上,并非如此。在这种情况下,括号是完全多余的,因为只有一个运算符in。当您有更多运算符时,可以使用括号来设置运算顺序。 (1+2)*3 == 9

(char in vowels) for char in string is not a valid generator outside of a function call.

事实上确实如此。在函数调用中,当生成器是唯一的参数时,您可以跳过额外的括号。所以下面两行的效果是一样的。

any(char in vowels for char in string)
any((char in vowels for char in string))

在函数调用之外,生成器必须有括号。

(char in vowels for char in string)

关于python - 为什么以下 Python 生成器表达式可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35120926/

相关文章:

python - 使用 Python 的 Popen 类从 Django 调用 Matlab 脚本

python - 我可以使用生成器表达式来打印字典列表的键、值对吗?

python - 调用返回列表的函数的生成器表达式

python - Neo4J 通过索引中节点的最短路径

python - 警告 : Some characters could not be decoded, 并被替换字符替换

python - 列表(生成器)的意外输出

python - 如何对集合的可变大小部分求和?

python - 将生成器表达式传递给 all()

python - 值错误 : too many values to unpack , 电子邮件验证

python - 打印由随机数选择的变量