作为一名Python和Numpy的开发者,我经常使用的一个特性是布尔掩码。
这里提供一个Python的示例:
>>> mylist = np.array([50, 12, 100, -5, 73])
>>> mylist == 12
array([False, True, False, False, False]) # A new array that is the result of ..
# .. comparing each element to 12
>>> mylist > 0
array([True, True, True, False, True]) # A new array that is the result of ..
# .. comparing each element to 0
>>> mylist[mylist == 12]
array([12]) # A new array of all values at indexes ..
# .. where the result of `mylist == 12` is True
>>> mask = mylist != 100 # Save a mask
>>> map(foo, mylist[mask]) # Apply `foo` where the mask is truthy
通常情况下,当使用另一个与其大小相同的数组对np.array
进行索引时,将返回一个新数组,其中包含掩码数组值为真的那些索引处的元素。
在JavaScript中,我可以使用Array.prototype.map
和Array.prototype.filter
实现类似的功能,但代码更冗长,而且我的掩码会被破坏。
-> mylist = [50, 12, 100, -5, 73]
-> mylist.map(item => item == 12)
<- [false, true, false, false, false] // mylist == 12
-> mylist.filter(item => item == 12)
<- [12] // mylist[mylist == 12]
-> mask = mylist.map(item => item == 12)
-> mylist.filter(item => mask.unshift())
<- [12] // mylist[mask]
-> mask
<- [] // Mask isn't reusable
在javascript中,是否有更好的方法来应用数组掩码,还是我必须每次复制掩码并使用filter
和map
?
.unshift()
可以实现这个功能 - 否则我需要一个掩码条目的索引。 - Zev IsertArray.prototype.maskFilter
,它只需要接受索引即可。 - RobGmap
和filter
,对吧? - Zev Isert