【问题标题】:Python: Something went wrong somewhere in the list comprehension?Python:列表理解中的某个地方出了问题?
【发布时间】:2013-06-03 01:44:22
【问题描述】:
>>> [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)True2 in sieve(100)True,所以列表推导式中的if 子句是False。但是为什么2 仍然在列表理解的输出中?

【问题讨论】:

    标签: python list-comprehension primes


    【解决方案1】:

    好吧,一开始听起来很疯狂,但是:

    >>> 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 &lt; 2 &lt;= 3。还有你的表情

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

    意思

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

    这是True

    【讨论】:

    • 谢谢。但是,1 不在 sieve(100) 中。是否还有其他可能出错的地方?
    • @SylvesterVLowell 好吧,可能是以下之一:1)sieve(100) 不仅包含整数,还包含布尔值True; 2) litheor(2) 返回 2 而不是布尔值,sieve(100) 包含 0。我看不到任何其他选择。请告诉我们您对sievelitheor 的定义?
    • @SylvesterVLowell 哦等等……你是对的……这太疯狂了……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2018-11-19
    • 2017-11-25
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多