Python AND operator on two boolean lists - how?

前端 未结 9 2115
感动是毒
感动是毒 2020-11-28 09:36

I have two boolean lists, e.g.,

x=[True,True,False,False]
y=[True,False,True,False]

I want to AND these lists together, with the expected o

9条回答
  •  無奈伤痛
    2020-11-28 10:22

    You could use numpy:

    >>> import numpy as np
    >>> x=np.array([True,True,False,False])
    >>> y=np.array([True,False,True,False])
    >>> x & y
    array([ True, False, False, False], dtype=bool)
    

    Numpy allows numerical and logical operations on arrays such as:

    >>> z=np.array([1,2,3,4])
    >>> z+1
    array([2, 3, 4, 5])
    

    You can perform bitwise and with the & operator.

    Instead of a list comprehension, you can use numpy to generate the boolean array directly like so:

    >>> np.random.random(10)>.5
    array([ True,  True,  True, False, False,  True,  True, False, False, False], dtype=bool)
    

提交回复
热议问题