两个布尔列表之间的逻辑运算 [英] Logical operation between two Boolean lists
本文介绍了两个布尔列表之间的逻辑运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到一个奇怪的结果,我尝试将and
或or
运算符应用于python中的2个布尔值列表.实际上,我得到的与预期完全相反.
I get a weird result and I try to apply the and
or the or
operator to 2 Boolean lists in python. I actually get the exact opposite of what I was expecting.
[True, False, False] and [True, True, False]
> [True, True, False]
[True, False, False] or [True, True, False]
> [True, False, False]
那正常吗?如果是,为什么?
Is that normal, and if yes, why?
推荐答案
您的列表不是比较每个单独的值,而是比较列表中值的存在.
Your lists aren't comparing each individual value, they're comparing the existence of values in the list.
对于任何真实变量a
和b
:
a and b
> b #The program evaluates a, a is truthy, it evaluates b, b is truthy, so it returns the last evaluated value, b.
a or b
> a #The program evaluates a, a is truthy, so the or statement is true, so it returns the last evaluated value, a.
现在,真实性取决于类型.例如,整数对于my_int != 0
是真实的,而对于my_int == 0
是虚假的.因此,如果您有:
Now, truthy depends on the type. For example, integers are truthy for my_int != 0
, and are falsy for my_int == 0
. So if you have:
a = 0
b = 1
a or b
> b #The program evaluates a, a is falsy, so the or statement goes on to evaluate b, b is truthy, so the or statement is true and it returns the last evaluated value b.
这篇关于两个布尔列表之间的逻辑运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文