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)
이 어떻게 그렇게 그파이썬은
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