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)
如何实施__iter__
以便
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
,并且会使search()
的代码更整洁
此外,他们还应该使用其他任何魔术方法吗? (除__str__
之外,我在迭代工作后就这样做了)
答案 0 :(得分:0)
您可以像这样实施__iter__()
:
from itertools import chain
def __iter__(self):
return chain.from_iterable(self.matrix)
itertools.chain.from_iterable()
采用可迭代的迭代次数并将它们组合在一起。它创建了一个生成器,因此不会使用额外的内存。