假设我有矩阵,我想要下面的结果。你知道吗
我不知道如何使用一个有效的循环来获得结果矩阵,在这个循环中,我获取任何给定的columnstodele和rowsToDelete数组。我已经尝试了很多不同的方法,我遇到的主要问题是当我使用矩阵.pop()整行或整列移动,因此矩阵最终会弹出一个我想要的不同行或列。你知道吗
到目前为止,只有当rowsToDelete或columnsToDelete中只有一个值时,我才能成功。你知道吗
例如,如果给我一个矩阵:
matrix = [[1, 0, 0, 2],
[0, 5, 0, 1],
[0, 0, 3, 5]]
rowsToDelete = [1]
columnsToDelete = [0, 2]
#The result should be [[0,2],
# [0,5]]
rows = [row for row in matrix]
#print rows
# if there is only one row to delete this is faster
if len(rowsToDelete) <= 1:
for i in rowsToDelete:
matrix.pop(i)
# if there is only one column to delete this is faster
if len(columnsToDelete) <= 1:
for row in matrix:
for col_value in row:
for i in columnsToDelete:
if col_value == i:
row.pop(col_value)
for i in columnsToDelete:
row.pop(i)
#answer should be [[0, 2],
# [0, 5]]
如果只给出一种情况,那么很容易做到,但是解决方案应该采用columnstodele=[ints]的任何数组和rowsToDelete=[ints]的任何数组,并删除这些列和行。你知道吗
你没有告诉我们你真正关心的问题。你知道吗
听起来你的要求是
你提供的例子很小。我假设你真的在操纵一个超过一千行和列的东西。我假设你在重复这样做,尽管你的问题有点含糊,你真正关心的是什么。你知道吗
使用C库(例如numpy)会很快,因为它消除了解释器的开销,但您已经排除了这一点。你知道吗
考虑一下从矩阵到dict的开销:
然后您可以根据需要遍历行或列索引到
del d[(r, c)]
。如果需要的话,会增加将dict转换回矩阵的开销。你知道吗编辑:下面是我描述的“输出数组的副本,删除行和列”复制方法。你知道吗
相关问题 更多 >
编程相关推荐