Case of bool Array Inversion in python

  • 2021-09-20 20:51:01
  • OfStack

Inversion operation of bool array in python

Since the number 0 is used in Python, 1 stands for Flase and Ture. Therefore, bool arrays cannot be directly inverted like matlab1.


a=np.array([False,True,False,True,False])

To reverse a, the simplest operation is


b=(a==False)
print(b)
[ True False True False True]

Added: python Method for inverting Boolean arrays True False (b= (a==False)


a=[True,True,False,False]
a=np.array(a)
b=(a==False)
print(b) # [False False True True]
print(b.tolist()) # [False, False, True, True]

Supplement: Transformation of list of python basic grammar (inverse\ slice, etc.)

How the list accesses values in reverse:

For example:

There is an list = [1, 2, 3, 4, 5, 6, 7, 7, 8] How to access from the first to the third from the bottom? The output I want should be [8, 7, 7]

Just use slices:


list[::-1][:3]
list[-3:][::-1]

list [::-1], in essence, the step size is-1 for slicing


Related articles: