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

2024-04-25 09:09:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

示例:给定产品可以是['S-AA', 'A-a', 'A-b']

现在我要填两套:

  1. 终端(仅包含来自givenProductions的小写字母)和
  2. 非终结符(仅包含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

正确的写作方法是什么?你知道吗


Tags: and字符串inforifprod大写字母ch
1条回答
网友
1楼 · 发布于 2024-04-25 09:09:29

如果你不在乎结果,列出理解是绝对没有用的。只需将其写为常规的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}

相关问题 更多 >