我有一个名为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
正确的写作方法是什么?你知道吗
如果你不在乎结果,列出理解是绝对没有用的。只需将其写为常规的
for
循环:请注意,两个
for
循环的顺序已更改!如果你真的想使用列表理解,你也必须这样做。不需要打印,只需用None
(反正print()
产生)完成三元。此外,理解列表需要方括号([]
):请注意,这将创建并丢弃
None
元素的列表。使用集合理解({}
)的内存效率更高,但CPU效率更低。你知道吗相关问题 更多 >
编程相关推荐