任何人都可以解释列表理解的内部工作原理,用于存在 if-else 的情况和其他只有 if 条件的情况吗?

Can anyone explain the internal working of list comprehension for cases where there's if-else and the other where there's only if condition?

我有以下3个表达式:

['-'+i+'-' if int(i)%2==0 else i for i in str(num).strip('-')]~~~~(1)

[i if i in ar and ar[i]>4 for i in s] ~~~~~(2),(其中ar是一张地图)

[i if i in ar and ar[i]>4 else continue for i in s]~~~~~~(3)

只有表达式 (1) 有效。其余两个没有。但是,如果我将表达式 (2) 重写如下:

[i for i in s if i in ar and ar[i]>4],效果很好

我有兴趣了解它的内部工作原理。

['-'+i+'-' if int(i)%2==0 else i for i in str(num).strip('-')] 因为 else 而起作用。在这种情况下,它使用条件表达式 [0],而不是理解列表的正常语法。 “列表理解由括号组成,括号中包含一个表达式,后跟一个 for 子句,然后是零个或多个 for 或 if 子句”[1]

正常的形式是[expression_statement forloop if_filter],对吧? 所以你应该

而不是 (2)
[i for i in s if i in ar and ar[i]>4]

相当于

alist = []
for i in s:
    if i in ar and ar[i]>4]:
        alist.append(i)

[0] https://docs.python.org/3/reference/expressions.html#conditional-expressions

[1] https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions