【问题标题】:([False, True] and [True, True]) evaluates to [True, True]([False, True] 和 [True, True]) 计算结果为 [True, True]
【发布时间】:2020-12-10 07:48:21
【问题描述】:

我在 python 3 中观察到以下行为:

>>> ([False, True] and [True, True])
[True, True]

>>> ([False, True] or [True, True])
[False, True]

我的预期正好相反:

[False, True] and [True, True] = [False and True, True and True] = [False, True]
[False, True] or [True, True] = [False or True, True or True] = [True, True]

观察到的行为有什么意义,我怎样才能达到预期的行为?

【问题讨论】:

  • 为什么你期待[False, True] and [True, True] = [False and True, True and True]
  • @juanpa.arrivillaga 这就是它在 R 和 Fortran 中的工作方式。他们逐元素评估向量。
  • R 和 Fortran 使用的是数组,而不是普通的旧列表(因此 numpy 填补了空白)

标签: python python-3.x boolean


【解决方案1】:

每个列表都被作为一个整体进行评估。 [False, True] 是 True,[True, True] 也是,因为只有一个空列表是 False。

and 返回最后一个 True 元素,但 or 返回第一个。

【讨论】:

  • 我如何评估元素?
  • @rvbarreto 你需要引入一个循环。 zip 可能有用。
  • 这些列表都不是True。他们是真的。不清楚你所说的 True 是什么意思。
  • @superbrain 在布尔上下文中使用时,它们都评估为True,因为它们不为空。
  • 我想这可能是正确的,尽管据我所知这是一个实现细节。例如documentation of if 只谈论真实,而不是关于True
【解决方案2】:

Python 不提供对列表的元素操作。您可以使用列表推导:

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

请注意,其他地方推荐的 np.bitwise_and 大约是一个数量级

【讨论】:

  • 这个问题的问题是list(zip(l1, l2)) == list(l1, l2),所以很难知道如何真正循环遍历所有内容
  • @PaulH 我不确定你的意思。 list(l1, l2) 首先是非法的。
  • 对不起,我的意思是 list(zip(l1, l2)) == [l1, l2] 用于提供的示例数据。所以很难知道 OP 实际进行了哪些比较。
【解决方案3】:

你想使用 numpy.标准库 python 正在评估:

bool([False, True]) and bool([True, True])

由于两者都是 True,所以它选择最后一个(试试1 and 2

如果你这样做了:

import numpy
numpy.bitwise_and([False, True], [True, True])

你会得到你想要的。

如果你不想使用numpy,你需要写一个列表推导或者循环:

result = [(x and y) for x, y in zip([False, True], [True, True])]

【讨论】:

    【解决方案4】:

    来自the reference

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

    您的表达式([False, True] and [True, True]) 是一个x and y 表达式,其中您的x 是[False, True],而您的y 是[True, True]。现在 x 是假的,还是真的?同样来自该文档:

    以下值被解释为假:FalseNone、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集)。所有其他值都被解释为 true。

    所以 x 为真,因此 and 操作返回 y。这正是你得到的。

    or 也是如此。

    另一种获得所需元素操作的方法:

    >>> x, y = [False, True], [True, True]
    >>> from operator import and_, or_
    >>> [*map(and_, x, y)]
    [False, True]
    >>> [*map(or_, x, y)]
    [True, True]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      • 2017-07-29
      • 2017-05-02
      • 2012-02-27
      相关资源
      最近更新 更多