简体   繁体   中英

Where can I find the formal grammar of list comprehension in Python?

我在哪里可以找到Python的形式语法,特别是List Comprehension?

Here's the full grammar (of Python 2.7.3):

http://docs.python.org/reference/grammar.html

The following rules are involved in parsing the general syntax of a list comprehension:

First, to parse the entire expression, which is an atom :

atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [listmaker] ']' |
       '{' [dictorsetmaker] '}' |
       '`' testlist1 '`' |
       NAME | NUMBER | STRING+)

Second, to parse the actual content of the comprehension, the listmaker , and the rules it uses:

listmaker: test ( list_for | (',' test)* [','] )
list_iter: list_for | list_if
list_for: 'for' exprlist 'in' testlist_safe [list_iter]
list_if: 'if' old_test [list_iter]

Beyond that you go back to general parsing expressions, eg exprlist .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM