This article mainly introduces the two-dimensional list in Python how to get the composition of sub-region elements, the article gives a detailed introduction and sample code, I believe that everyone's understanding and learning has a certain reference value, the need for friends below to see it together.
Used NumPY
should be known, in a two-dimensional array can easily use the area slicing function, such as:
This feature is not supported in the Python standard library List
and List
can only be sliced in one-dimensional ways:
But sometimes I just want to use this feature, but I don't want to introduce it NumPY
. In fact, I can do that in Python. At this point, you only need to implement a special method in a class __getitem__
:
Class Array: "" "Implements __GETITEM__, supports sequence acquisition elements, slice, etc." "" "Def __init__ (Self, LST): self.__coll = lst def __repr__ (self): c6/> "" "Display List" "" return ' {!r} '. Format (self.__coll) def __getitem__ (self, Key): "" " Gets the Element" "" slice1, Slice2 = Key row1 = Slice1.start row2 = slice1.stop col1 = slice2.start col2 = slice2.stop return [self . __coll[r][col1:col2] for R in range (Row1, row2)]
Try:
A = Array ([[' A ', ' B ', ' C ', ' d '], [' E ', ' f ', ' g ', ' H '], [' I ', ' j ', ' K ', ' l '], [' m ', ' n ', ' o ', ' P '], [' Q ', ' R ', ' s ', ' t '], [' u ', ' V ', ' w ', ' X ']) print (A[1:5, 1:3])
__getitem__
an explanation of the official documentation:
In short, it is primarily used to get self[key]
the value.
I am here in order to highlight the problem, only the key code, exception judgment, boundary check, condition restrictions, and even some other special methods 如__setitem__
, __delitem__
and other __len__
code, depending on the actual situation to be added.
Of course, there are other ways of dealing with the code, as shown below, but the different methods undoubtedly give me a variety of options under various scenarios.
A = [[' A ', ' B ', ' C ', ' d '], [' E ', ' f ', ' g ', ' H '], [' I ', ' j ', ' K ', ' l '], [' m ', ' n ', ' o ', ' P '], [' Q ', ' R ', ' s ', ' t '], [' u ', ' V ', ' w ', ' x ']]SL = lambda row1, row2, col1, col2, lst: \ [lst[r][col1:col2] for R in range (Row1, R OW2)]SL (1, 5, 1, 3, a)