在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]
>>> ???
最佳答案
如果您可以使用第三方模块,请查看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')
关于python - 逻辑向量作为Python中的索引吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20503041/