如何在不使用numpy或任何包的情况下对python嵌套列表(或矩阵)进行切片

2024-10-05 14:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有矩阵,我想要下面的结果。你知道吗

我不知道如何使用一个有效的循环来获得结果矩阵,在这个循环中,我获取任何给定的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]的任何数组,并删除这些列和行。你知道吗


Tags: inforifisvalue矩阵col数组
1条回答
网友
1楼 · 发布于 2024-10-05 14:30:24

你没有告诉我们你真正关心的问题。你知道吗

听起来你的要求是

  1. 快速删除行或列
  2. 没有C库的支持,比如numpy

你提供的例子很小。我假设你真的在操纵一个超过一千行和列的东西。我假设你在重复这样做,尽管你的问题有点含糊,你真正关心的是什么。你知道吗

使用C库(例如numpy)会很快,因为它消除了解释器的开销,但您已经排除了这一点。你知道吗

考虑一下从矩阵到dict的开销:

d = {}
for r, row in enumerate(matrix):
    for c, val in row:
        d[(r, c)] = val

然后您可以根据需要遍历行或列索引到del d[(r, c)]。如果需要的话,会增加将dict转换回矩阵的开销。你知道吗

编辑:下面是我描述的“输出数组的副本,删除行和列”复制方法。你知道吗

#! /usr/bin/env python3


def delete_r_c(matrix, omit_rows, omit_cols):
    omit_rows = set(omit_rows)  # a list doesn't offer O(1) lookups
    omit_cols = set(omit_cols)
    ret = []
    for r, row in enumerate(matrix):
        if r not in omit_rows:
            ret.append([val
                        for c, val in enumerate(row)
                        if c not in omit_cols])
    return ret


if __name__ == '__main__':
    print(delete_r_c(
        [[1, 0, 0, 2],
         [0, 5, 0, 1],
         [0, 0, 3, 5]],
        omit_rows={1},
        omit_cols={0, 2}))

相关问题 更多 >