三元运算符 python3.5 的列表理解

List comprehension for ternary operator python3.5

我有一个名为 givenProductions 的字符串列表。每个字符串都有一个大写字母和“-”,并且可能包含一个小写字母。

示例:givenProductions 可以是 ['S-AA', 'A-a', 'A-b']

现在我要补两套:

  1. 终端(仅包含来自 givenProductions 的小写字母)和
  2. nonTerminals(仅包含来自 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 prod in givenProductions:
    for ch in prod:
        if ch >= 'a' and ch <= 'z':
            terminals.append(ch)
        elif ch != '-':
            nonTerminals.append(ch)

注意两个for循环的顺序变了!如果您真的想要使用列表理解,您也必须这样做。不需要打印,只需用 None 完成三元组(无论如何 print() 都会产生)。此外,列表理解需要方括号 ([]):

>>> givenProductions = ['S-AA', 'A-a', 'A-b']
>>> terminals, nonTerminals = [], []
>>> [terminals.append(ch) if (ch >= 'a' and ch <= 'z') else nonTerminals.append(ch) if (ch != '-') else None for prod in givenProductions for ch in prod]
>>> terminals, nonTerminals
>>> print(terminals, nonTerminals)
['a', 'b'] ['S', 'A', 'A', 'A', 'A']

请注意,这会创建并丢弃 None 个元素的列表。使用集合理解 ({}) 的内存效率更高,但 CPU 效率较低。

>>> waste = {terminals.append(ch) if (ch >= 'a' and ch <= 'z') else nonTerminals.append(ch) if (ch != '-') else None for prod in givenProductions for ch in prod}
>>> print(waste)
{None}