在Python中提取2D-List/Matrix/List列表的一部分

Raf*_*ter 5 python list

我想在Python中提取二维列表(=列表列表)的一部分.我经常使用Mathematica,编写起来非常方便

matrix[[2;;4,10;;13]] 
Run Code Online (Sandbox Code Playgroud)

它将提取第二和第四行之间以及第10和第13列之间的矩阵部分.

在Python中,我刚刚使用过

[x[firstcolumn:lastcolumn+1] for x in matrix[firstrow:lastrow+1]]
Run Code Online (Sandbox Code Playgroud)

是否还有更优雅或有效的方法来做到这一点?

wer*_*ika 12

你想要的是numpy数组和切片运算符:.

>>> import numpy

>>> a = numpy.array([[1,2,3],[2,2,2],[5,5,5]])
>>> a
array([[1, 2, 3],
       [2, 2, 2],
       [5, 5, 5]])

>>> a[0:2,0:2]
array([[1, 2],
       [2, 2]])
Run Code Online (Sandbox Code Playgroud)