python 中的布尔列表运算
Boolean list operation in python
结果不应该一样吗?
没看懂。
[True,False] and [True, True]
Out[1]: [True, True]
[True, True] and [True,False]
Out[2]: [True, False]
不,因为那不是 and
操作在 python 中的工作方式。首先,它不会 and
单独列出列表项。其次,and
运算符在两个对象之间工作,如果其中一个为 False (evaluated as False 1) 它 returns 如果两者都是 True 它returns 第二个。这是一个例子:
>>> [] and [False]
[]
>>>
>>> [False] and []
[]
>>> [False] and [True]
[True]
x and y
: if x
is false, then x
, else y
如果您想对所有列表对应用逻辑运算,您可以使用 numpy 数组:
>>> import numpy as np
>>> a = np.array([True, False])
>>> b = np.array([True, True])
>>>
>>> np.logical_and(a,b)
array([ True, False], dtype=bool)
>>> np.logical_and(b,a)
array([ True, False], dtype=bool)
1. 在这里,由于您正在处理列表,因此空列表将被评估为 False
结果不应该一样吗? 没看懂。
[True,False] and [True, True]
Out[1]: [True, True]
[True, True] and [True,False]
Out[2]: [True, False]
不,因为那不是 and
操作在 python 中的工作方式。首先,它不会 and
单独列出列表项。其次,and
运算符在两个对象之间工作,如果其中一个为 False (evaluated as False 1) 它 returns 如果两者都是 True 它returns 第二个。这是一个例子:
>>> [] and [False]
[]
>>>
>>> [False] and []
[]
>>> [False] and [True]
[True]
x and y
: ifx
is false, thenx
, elsey
如果您想对所有列表对应用逻辑运算,您可以使用 numpy 数组:
>>> import numpy as np
>>> a = np.array([True, False])
>>> b = np.array([True, True])
>>>
>>> np.logical_and(a,b)
array([ True, False], dtype=bool)
>>> np.logical_and(b,a)
array([ True, False], dtype=bool)
1. 在这里,由于您正在处理列表,因此空列表将被评估为 False