from collections.abc import Sequence
class Map(Sequence):
""" Represents a map for a floor as a matrix """
def __init__(self, matrix):
""" Takes a map as a matrix """
self.matrix = matrix
self.height = len(matrix)
self.width = len(matrix[0])
super().__init__()
def __getitem__(self, item):
""" Needed by Sequence """
return self.matrix[item]
def __len__(self):
""" Needed by Sequence """
return len(self.matrix)
def search(self, entity):
""" Returns a generator of tuples that contain the x and y for every element in the map that matches 'entity' """
for row in range(self.height):
for column in range(self.width):
if matrix[row][column] == entity:
yield (row, column)
# Examples
gmap = Map([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]])
for entity in gmap:
print(entity)
がどのように私はそれがは、Pythonは
for entity in gmap:
print(entity)
利回り0 0 0 0 1 0 0 0 0
なく
[0, 0, 0]
[0, 1, 0]
[0, 0, 0]
これはSequence
をサブクラス化する必要から私を救う__iter__
を実装することができます行列クラスを反復処理し、コードになるだろうsearch()
neater
さらに、私が使用しなければならない他の魔法の方法もありますか?あなたがそうのような__iter__()
を実装することができる
これは本当に悪い考えです。あなたの '__iter__'と' __getitem__'はお互いに矛盾しています。 – user2357112
また、それは実際には何の検索もしません。 – user2357112