【问题标题】:Python list of booleans comparison gives strange results布尔比较的 Python 列表给出了奇怪的结果
【发布时间】:2012-10-05 14:45:08
【问题描述】:

我试试:

[True,True,False] and [True,True,True]

然后得到 [对,对对]

但是

[True,True,True] and [True,True,False]

给予

[True,True,False]

不太清楚为什么它会给出这些奇怪的结果,即使在查看了其他一些 python 布尔比较问题之后也是如此。 Integer 做同样的事情(替换上面的 True -> 1 和 False ->0 并且结果是一样的)。我错过了什么?我显然想要

[True,True,False] and [True,True,True]

评估为

[True,True,False]

【问题讨论】:

    标签: python list comparison boolean


    【解决方案1】:

    任何填充列表的计算结果为TrueTrue and x 产生 x,第二个列表。

    【讨论】:

      【解决方案2】:

      [True, True, False] 被评估为布尔值(因为and 运算符),并且评估为True,因为它是非空的。与[True, True, True] 相同。任一语句的结果就是 and 运算符之后的结果。

      您可以为列表ab 执行类似[ai and bi for ai, bi in zip(a, b)] 的操作。

      【讨论】:

        【解决方案3】:

        and 如果它们都被评估为True,则返回最后一个元素。

        >>> 1 and 2 and 3
        3
        

        这同样适用于列表,如果它们不为空(如您的情况),则将其评估为 True

        【讨论】:

          【解决方案4】:

          Python 通过将其布尔值短路并将结果表达式作为结果来工作。 填充列表的计算结果为 true,并将结果作为第二个列表的值。看看这个,当我刚刚交换了你的第一个和第二个列表的位置时。

          In [3]: [True,True,True] and [True, True, False]
          Out[3]: [True, True, False]
          

          【讨论】:

            【解决方案5】:

            来自Python documentation

            表达式 x 和 y 首先计算 x;如果 x 为假,则返回其值;否则,计算 y 并返回结果值。

            您将获得第二个返回值。

            附:我以前也从未见过这种行为,我必须自己查一下。我天真的期望布尔表达式会产生布尔结果。

            【讨论】:

              【解决方案6】:

              据我所知,您需要浏览列表。尝试这种列表理解:

              l1 = [True,True,False]
              l2 = [True,True,True]
              res = [ x and y for (x,y) in zip(l1, l2)]
              print res
              

              【讨论】:

                【解决方案7】:

                其他人已经解释了发生了什么。以下是一些获得您想要的东西的方法:

                >>> a = [True, True, True]
                >>> b = [True, True, False]
                

                使用 listcomp:

                >>> [ai and bi for ai,bi in zip(a,b)]
                [True, True, False]
                

                and_ 函数与map 一起使用:

                >>> from operator import and_
                >>> map(and_, a, b)
                [True, True, False]
                

                或者我喜欢的方式(虽然这需要numpy):

                >>> from numpy import array
                >>> a = array([True, True, True])
                >>> b = array([True, True, False])
                >>> a & b
                array([ True,  True, False], dtype=bool)
                >>> a | b
                array([ True,  True,  True], dtype=bool)
                >>> a ^ b
                array([False, False,  True], dtype=bool)
                

                【讨论】:

                  猜你喜欢
                  • 2017-02-02
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-12-19
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多