6
>>> [l for l in range(2,100) if litheor(l)!=l in sieve(100)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> 2 in sieve(100)
True
>>> litheor(2)
True

所以litheor(2)isTrue2 in sieve(100)is True,所以if列表推导中的子句 is False。但是为什么2仍然在列表推导的输出中?

4

1 回答 1

11

好的,起初这听起来很疯狂,但是:

>>> True != 2 in [2,3,5]
True
>>> (True != 2) in [2,3,5]
False
>>> True != (2 in [2,3,5])
False

当您意识到这不是一个简单的优先级问题时,查看 AST 是唯一剩下的选择:

>>> ast.dump(ast.parse("True != 2 in [2,3,5]"))
"Module(body=[Expr(value=
Compare(left=Name(id='True', ctx=Load()), ops=[NotEq(), In()], comparators=[Num(n=2), List(elts=[Num(n=2), Num(n=3), Num(n=5)], ctx=Load())])
)])"

这里有一个小提示:

>>> ast.dump(ast.parse("1 < 2 <= 3"))
'Module(body=[Expr(value=
Compare(left=Num(n=1), ops=[Lt(), LtE()], comparators=[Num(n=2), Num(n=3)])
)])'

所以,事实证明,True != 2 in [2,3,5]被解释为类似于1 < 2 <= 3。还有你的表情

litheor(l) != l in sieve(100)

方法

litheor(l) != l and l in sieve(100)

这是True

于 2013-06-06T21:29:14.407 回答