【发布时间】:2018-10-01 11:48:15
【问题描述】:
我有一个名为givenProductions 的字符串列表。每个字符串都有一个大写字母和“-”,并且可能包含一个小写字母。
示例:givenProductions 可以是['S-AA', 'A-a', 'A-b']
现在我想填充两组:
- 终端(仅包含来自
givenProductions的小写字母)和 - 非终端(仅包含来自
givenProductions的大写字母)
只有一行
我试过这个...
terminals.append(ch) if (ch >= 'a' and ch <= 'z') else nonTerminals.append(ch) if (ch != '-') else print() for ch in prod for prod in givenProductions
导致语法错误
File "<stdin>", line 2
terminals.append(ch) if (ch >= 'a' and ch <= 'z') else nonTerminals.append(ch) if (ch != '-') else print ('-') for ch in prod for prod in givenProductions
^
SyntaxError: invalid syntax
正确的写法是什么?
【问题讨论】:
-
产品、终端和符号...我闻到了上下文无关语言/语法...
-
是的,我正在为 lr(0) 解析器编写一个程序……这只是该代码的一部分
-
与CFGs有关,只是想缩短代码长度。
-
发布你想要的输出
-
次要旁注:这是 Python 支持链式比较的经典案例;测试
'a' <= ch <= 'z'将等效于ch >= 'a' and ch <= 'z',但更直接地可读为测试ch是否出现在给定范围内(并且效率更高,因为它只加载一次ch)。
标签: python python-3.x list-comprehension ternary-operator