([False, True] 和 [True, True]) 的计算结果为 [True, True]

([False, True] and [True, True]) evaluates to [True, True]

我在 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] 是 True,[True, True] 也是,因为只有一个空列表是 False。

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

您想使用 numpy。标准库 python 正在评估:

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

因为两者都是 True,它选择最后一个(尝试 1 and 2

如果你这样做了:

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

你会得到你想要的。

如果不想用numpy,需要自己写一个list comprehension或者loop:

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

Python 不提供对列表的 element-wise 操作。您可以使用列表理解:

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

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

来自 the reference:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

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

the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

所以 x 为真,因此 and 操作 returns y。这正是您得到的。

同样适用于 or

获得所需 element-wise 操作的另一种方法:

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