In R we can use a logical vector as an index to another vector or list.
Is there an analogous syntax in Python?
## In R:
R> LL = c("A", "B", "C")
R> ind = c(TRUE, FALSE, TRUE)
R> LL[ind]
[1] "A" "C"
## In Python
>>> LL = ["A", "B", "C"]
>>> ind = [True, False, True]
>>> ???
In pure Python, though, you might try this
[x for x, y in zip(LL, ind) if y]
If ind and LL are Numpy arrays, then you can go LL[ind] just like in R.
import numpy as np
LL = np.array(["A", "B", "C"])
ind = np.array([True, False, True])
LL[ind] # returns array(['A', 'C'], dtype='|S1')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With