Pythonic way to extract 2D array from list

Viewed 545

Say I have a list which contains 16 elements:

lst=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P']

This list represents a 4 x 4 array where all elements have been put into a 1D list. In its array form it has this form:

'A', 'B', 'C', 'D'
'E', 'F', 'G', 'H'
'I', 'J', 'K', 'L'
'M', 'N', 'O', 'P' 

I want to extract a sub-matrix from this 1D list as another 1D list which always starts at the first element.

e.g. Extracting a 2 x 2 matrix from lst:

'A', 'B', 'E', 'F'

Or extracting a 3 x 3 matrix from lst:

'A', 'B', 'C', 'E', 'F', 'G', 'I', 'J', 'K'

To achieve this I use numpy to resize the list into an array, extract the submatrix and then flatten back down again:

import numpy as np

# The size of the matrix represented by lst
init_mat = 4
# Desired matrix size to extract
mat_size = 2
A = np.resize(lst,(init_mat,init_mat))
B = A[0:mat_size, 0:mat_size].flatten()
C = map(str,B)

This works but I was wondering if there was a more pythonic way to do this, as I do not think this method will scale well with matrix size.

3 Answers
Related