python-3.x - 在 Python 中使用掩码从矩阵中获取列表
问题描述
在Python中使用另一个矩阵作为掩码从矩阵中获取列表的最快方法是什么?
列表的顺序必须按列。
例子:
matrix = ([1, 2, 3],
[4, 5, 6],
[7, 8, 9])
mask1 = ([0, 1, 0],
[1, 0, 1],
[0, 0, 0])
mask2 = ([0, 0, 0],
[1, 1, 1],
[0, 0, 0])
mask3 = ([0, 0, 1],
[0, 1, 0],
[1, 0, 0])
output1 = [4, 2, 6]
output2 = [4, 5, 6]
output3 = [7, 5, 3]
解决方案
请注意,您matrix/mask
看起来像一个元组,这可能不适合 numpy 向量化。让我们尝试将它们转换为np.array
:
matrix = np.array(matrix)
def get_mask(mask, matrix=matrix):
# .T so we can get the output ordered by columns
return matrix.T[np.array(mask, dtype=bool).T]
get_mask(mask1, matrix)
输出:
array([4, 2, 6])
推荐阅读
- rust - 给定 Path 实例编写 File 的最佳方法是什么?
- go - 将 YAML 清单解析为 Kubernetes []client.Object
- angular - 当我在Angular .kendo上下文菜单中单击它时如何创建一个插入单词的函数
- python - Python - 多处理多个文件夹
- php - Amazon SES 模板 URL {{values}} 未替换为已发送电子邮件中的值
- node.js - Mongoose 返回 "new ObjectId("//id")" 而不仅仅是 id
- vue.js - Vuejs Webpack 构建输出几个同名的类
- postgresql - 在 postgresql 中运行 plpython 函数时出错
- netsuite - Netsuite 权限错误“此客户或潜在客户不属于您的组”
- android - Flutter - 在后台模式下在屏幕上显示之前更改推送通知的内容