python - 用掩码合并两个列表
问题描述
如果有一个布尔列表两个列表
两个列表长度之和等于掩码长度有没有一种有效的方法来合并这两个列表?
例子
mask : array([False, True, True, False, False])
list a : array([3, 4])
list b : array([1, 2, 5])
if True fill in a if False fill in b
output : array([1, 3, 4, 2, 5])
直觉方式
a_count = 0
b_count = 0
output = np.zeros(mask.shape)
for i in range(len(mask)):
if mask[i] == True:
output[i] = a[a_count]
a_count += 1
elif mask[i] == False:
output[i] = b[b_count]
b_count += 1
但它的速度很慢。我怎样才能提高速度?
解决方案
您可以使用数组和掩码来做到这一点:
mask = np.array([False, True, True, False, False])
a = np.array([3, 4])
b = np.array([1, 2, 5])
# create output array
out = np.empty_like(mask, dtype=int)
# select elements from out that are True in mask -> set them to a
out[mask] = a
# if False set to b
out[~mask] = b
out
>>> array([1, 3, 4, 2, 5])
推荐阅读
- php - 如何使用 .htaccess 重写规则?
- web3swift - 如何在 web3swift 中使用自定义 json 合约
- excel - 使用 VBA 仅复制和粘贴具有值的单元格
- html - 旋转的 div 不粘在视口的右边界(向左平坦)
- react-native - Redux 和 React Native - 如何将回调连接到调度
- docker - docker-compose 与 vue-cli 不工作
- php - PHP:我可以在它的第一个深度分割一个 JSONstring 而不必重新编码?
- apache-camel - Camel HTTPComponent 选项与 HTTPEndpoint 选项
- performance - 在 vuejs 的列表的每个元素中都有一个模态组件(默认情况下不呈现)可以吗?
- kubernetes - 如何标记 Kubernetes 节点?