列表列表的子矩阵(不带numpy)

2024-05-15 20:44:55 发布

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

假设我有一个矩阵,由如下列表组成:

>>> LoL=[list(range(10)) for i in range(10)]
>>> LoL
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

另外,假设我有一个名为LoLa的相同结构的numpy矩阵:

>>> LoLa=np.array(LoL)

使用numpy,我可以得到这样一个矩阵的子矩阵:

>>> LoLa[1:4,2:5]
array([[2, 3, 4],
       [2, 3, 4],
       [2, 3, 4]])

我可以用纯Python复制numpy矩阵片段,如下所示:

>>> r=(1,4)
>>> s=(2,5)
>>> [LoL[i][s[0]:s[1]] for i in range(len(LoL))][r[0]:r[1]]
[[2, 3, 4], [2, 3, 4], [2, 3, 4]] 

这不是世界上最容易阅读的东西,也不是最有效的东西

问:有没有一种更简单的方法(在纯Python中)将任意矩阵分割为子矩阵?


Tags: 方法innumpy列表forlennp世界
3条回答

做这个

submat=[[mat[i][j]表示j in range(index1,index2)]i in range(index3,index4)]

子矩阵将是原始大矩阵的矩形块(如果index3==index1和index2==index4,则为正方形)。

In [74]: [row[2:5] for row in LoL[1:4]]
Out[74]: [[2, 3, 4], [2, 3, 4], [2, 3, 4]]

您还可以通过定义list的子类来模拟NumPy的语法:

class LoL(list):
    def __init__(self, *args):
        list.__init__(self, *args)
    def __getitem__(self, item):
        try:
            return list.__getitem__(self, item)
        except TypeError:
            rows, cols = item
            return [row[cols] for row in self[rows]]

lol = LoL([list(range(10)) for i in range(10)])
print(lol[1:4, 2:5])

也会产生

[[2, 3, 4], [2, 3, 4], [2, 3, 4]]

使用LoL子类不会赢得任何速度测试:

In [85]: %timeit [row[2:5] for row in x[1:4]]
1000000 loops, best of 3: 538 ns per loop
In [82]: %timeit lol[1:4, 2:5]
100000 loops, best of 3: 3.07 us per loop

但速度并不是一切——有时候可读性更重要。

首先,可以直接使用slice对象,这有助于提高可读性和性能:

r = slice(1,4)
s = slice(2,5)
[LoL[i][s] for i in range(len(LoL))[r]]

如果你只是直接遍历列表列表,你可以这样写:

[row[s] for row in LoL[r]]

相关问题 更多 >