日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中二维数组如何按索引找元素_按索引或坐标访问二维数组中的元素

發布時間:2024/10/12 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中二维数组如何按索引找元素_按索引或坐标访问二维数组中的元素的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。