简体   繁体   中英

How does the following Python expression work?

I have got the following python expression in my code

import numpy as np  
a = np.array([1,0,1,0])  
b = np.array([True,False,False,True])
print a[b],b[a]  

The output i am getting looks like this:

[1 0] [False  True False  True]

I am not able to understand how this output is generated.
Can anybody explain it.

They are two difference cases

a[b] is logical indexing . The index b must be a boolean array, the same size as a . Each boolean value of b mean take/leave this element of a . That is: for each pair of values in a_i, b_i in vectors a, b : If b_i == True , add a_i to the output vector, otherwise ignore it.

b[a] is indexing with multiple values. Just like in normal python you can do b[0] to take the first value of b , in numpy you can use an array as index, to take multiple elements. in your case, this produces the same result as [b[1], b[0], b[1], b[0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM