在R
中,我们可以使用逻辑向量作为另一个向量或列表的索引
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]
>>> ???
答案 0 :(得分:4)
但是在纯Python中,你可以试试这个
[x for x, y in zip(LL, ind) if y]
如果ind
和LL
是Numpy数组,那么就像在R中一样LL[ind]
。
import numpy as np
LL = np.array(["A", "B", "C"])
ind = np.array([True, False, True])
LL[ind] # returns array(['A', 'C'], dtype='|S1')
答案 1 :(得分:3)
如果您可以使用第三方模块,请查看Numpy,特别是masked arrays:
>>> import numpy as np
>>> LL = np.array(["A", "B", "C"])
>>> ind = np.ma.masked_array([True, False, True])
>>> LL[ind]
array(['A', 'C'],
dtype='|S1')
或boolean indexing(由@mgilson帮助指出):
>>> # find indices where LL is "A" or "C"
>>> ind = np.array([True, False, True])
>>> LL[ind]
array(['A', 'C'],
dtype='|S1')