python中二维数组如何按索引找元素_按索引或坐标访问二维数组中的元素
設置
我正在用python編寫一個類來處理一個二維的布爾數組。在class Grid(object):
def __init__(self, length):
self.length = length
self.grid = [[False]*length for i in range(length)]
def coordinates(self, index):
return (index // self.length, index % self.length)
有時在我的應用程序中,通過項目的坐標來訪問它是有意義的,但有時通過它的索引訪問一個項目更有意義。我還經常需要一次偽造或篡改一批物品。在不使課程變得復雜的情況下,我可以這樣做:
^{pr2}$
第一步
當然,我想在我的Grid對象中添加一些mutator方法,這樣我就不必直接訪問對象內部并編寫一堆循環:def set_coordinate(self, row, col, value):
self.grid[row][col] = bool(value)
def set_index(self, i, value):
coords = self.coordinates(i)
self.set_coordinates(coords[0], coords[1], value)
def set_coordinates(self, coordinates, value):
for row, col in coordinates:
self.set_coordinate(row, col, value)
def set_indices(self, indices, value):
for i in indices:
self.set_index(i, value)
訪問器方法也很簡單。我可能還想添加一些語義上有意義的別名:def truthify_coordinate(self, row, col):
self.set_coordinate(row, col, True)
def falsify_coordinate(self, row, col):
self.set_coordinate(row, col, False)
def truthify_coordinates(self, coordinates):
self.set_coordinates(coordinates, True)
... etc ...
想法
我想創建一個名為set_item的方法,其中的位置可以是長度為2的iterable,表示坐標或一個標量索引。在def set_item(self, location, value):
try:
location = self.coordinates(location)
except TypeError:
pass
self.set_coordinates(location[0], location[1], value)
利與弊
這樣做的好處是(顯然)我不需要指定位置是一對坐標還是索引,所以當我一次設置一批位置時,它們不必都是同一時間。例如,以下內容:indices = [3, 5, 14, 60]
coordinates = [(1, 7), (4, 5)]
g.truthify_indices(indices)
g.truthify_coordinates(coordinates)
變成locations = [3, 5, (1, 7), 14, (4, 5), 60]
g.truthify(locations)
在我看來,這本書更干凈,更容易閱讀和理解。在
缺點之一是像g.truthify((2, 3))這樣的東西很難馬上破譯(它是設置一個坐標還是兩個索引?)。可能還有更多我沒想到的。在
問題
實現這個想法是Python式的嗎?還是我應該堅持明確區分索引和坐標?在
總結
以上是生活随笔為你收集整理的python中二维数组如何按索引找元素_按索引或坐标访问二维数组中的元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3协程 queue_使用ge
- 下一篇: windows下挂载ext4_WSL2