布尔值比较的Python列表给出了奇怪的结果 [英] Python list of booleans comparison gives strange results

查看:58
本文介绍了布尔值比较的Python列表给出了奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试:

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

并获取[True,True True]

and get [True, True True]

但是

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

给予

[True,True,False]

即使看了其他一些python布尔比较问题,也不太确定为什么会给出那些奇怪的结果.整数执行相同操作(替换上面的True-> 1和False-> 0,结果相同).我想念什么?我显然想要

Not too sure why it's giving those strange results, even after taking a look at some other python boolean comparison questions. Integer does the same (replace True -> 1 and False ->0 above and the results are the same). What am I missing? I obviously want

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

评估为

[True,True,False]

推荐答案

其他人已经解释了发生了什么.这里有一些获取您想要的东西的方法:

Others have explained what's going on. Here are some ways to get what you want:

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

使用listcomp:

Use a 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 ):

Or my preferred way (although this does require 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)

这篇关于布尔值比较的Python列表给出了奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆