In Python, how does one obtain the composition of subarea elements from a two-dimensional list?
UsedNumPYYou should know that you can easily use the area slicing function in a two-dimensional array, such:
This function is available in the Python standard libraryListIs not supported inListSlice operations can only be performed in one dimension:
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])
Official documentation__getitem__Explanation:
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)
Summary
The above is all the content of this article. One thing that attracts me in Python programming is that it is like a gold mine. It is very likely that some unexpected fun will come out when it is dug. I hope the content in this article will help you learn or use python. If you have any questions, please leave a message.