DragonKnight
DragonKnight

Reputation: 1870

How to print sub matrix in python?

Is there any short way in python to print sub matrix of a bigger matrix like this not using for loop?

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

sub1 = matrix[1:2][1:2] 
>>>desired answer: [[6,7][10,11]]
1   2  3   4
5  *6  7*  8 
9  *10 11* 12
13  14  15 16 

sub2 = matrix[2][1:3] 
>>>desired answer: [[7,11,15]]
1   2  3  4
5   6  *7* 8 
9  10 *11* 12
13 14 *15* 16 

extra: for the latter example, how to return it in reverse format not using reverse()? ie: [15,11,7] or [16,15,14],

Upvotes: 0

Views: 2566

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

For lists of lists, you can get your desired result like this:

>>> [s[1:3] for s in matrix[1:3]]
[[6, 7], [10, 11]]
>>>
>>> [s[2:3] for s in matrix[1:4]]
[[7], [11], [15]]
>>> 

Note that the latter is a vertical slice, so each element is wrapped in its own list. Also note that this is Python indexing, so the second limit in a range specifier is one higher than the last index in the slice.

Upvotes: 3

Related Questions