This article mainly introduces how to obtain the composition of sub-region elements in the two-dimensional list in Python. This article provides a detailed introduction and sample code, I believe that it has some reference value for everyone's understanding and learning. if you need it, let's take a look at it. This article mainly introduces how to obtain the composition of sub-region elements in the two-dimensional list in Python. This article provides a detailed introduction and sample code, I believe that it has some reference value for everyone's understanding and learning. if you need it, let's take a look at it.
UsedNumPY
You should know that you can easily use the area slicing function in a two-dimensional array, such:
But sometimes I just want to use this function, but I don't want to introduce it.NumPY
. In fact, I can also implement it in Python at this time. At this time, you only need to implement__getitem__
Special methods:
Class Array: "_ getitem __, supporting sequential element acquisition, Slice, and other features" def _ init _ (self, lst): self. _ coll = lst def _ repr _ (self): "Display List" "return '{! R }'. format (self. _ coll) def _ getitem _ (self, key): "Get 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])
In short, it is mainly used to obtainself[key]
.
I only list key code, exception judgment, boundary check, condition restriction, and other special methods to solve the problem.For example, _ setitem __
,__delitem__
And__len__
And other code, you need to add according to the actual situation.
Of course, there are other processing methods, as shown in the code below, but different methods undoubtedly give me a variety of options in 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, row2)]sl(1, 5, 1, 3, a)
For more information about how to obtain the composition of sub-region elements in the two-dimensional list in Python, refer to the PHP Chinese website!