gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:31:24 24 4
gpt4 key购买 nike

我有一个名为 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}

关于python - 三元运算符 python3.5 的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49947076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com