【问题标题】:python generator example with star expression带有星形表达式的python生成器示例
【发布时间】:2018-07-11 05:48:50
【问题描述】:

documentation中,生成器表达式的定义为

generator_expression ::=  "(" expression comp_for ")"

而在 grammar 中它被隐藏并读取

atom: ('(' [yield_expr|testlist_comp] ')' | .......
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

根据语法,"(" "*" 表达式 comp_for ")" 是一个有效的生成器表达式,但文档中没有详细说明。有人可以为我举一个带有星星的发电机的具体例子吗?

假设myList = ((1, 2, 3), (4, 5, 6)),例如考虑(*x for x in myList)

  1. myList 是一个原子
  2. for x in myList 匹配 comp_for 根据

    comp_for: 'for' exprlist 'in' or_test

  3. *x 匹配 star_expr 因此 test|star_expr

  4. *x for x in myList 匹配 testlist_comp
  5. 最后(*x for x in myList) 是一个有效的原子,因为它匹配'(' testlist_comp ')'

python 解释器给出 SyntaxError: iterable unpacking cannot be used in comprehension

【问题讨论】:

标签: python-3.x


【解决方案1】:

Python 中的合法语法与语法描述的并不完全相同。在 ast.c 中对 ast_error 的各种调用是语法允许但无效的案例示例。 “位置参数跟随关键字参数”是最熟悉的一种:语法中没有任何内容不允许

def foo(what=None, how):
    pass

但这确实会引发 SyntaxError(请参阅 this line in ast.c in the cpython source)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2019-10-05
    • 2014-04-02
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2021-04-26
    相关资源
    最近更新 更多