2016-09-21 2 views
0
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__()을 구현할 수

+0

정말 나쁜 생각입니다. '__iter__'와'__getitem__'은 서로 모순이됩니다. – user2357112

+0

또한 실제로 검색을 수행하지도 않습니다. – user2357112

답변

0

(나는 작업을 반복 취득 후 옆 __str__에서, 메신저 그 일) :

from itertools import chain 

def __iter__(self): 
    return chain.from_iterable(self.matrix) 

itertools.chain.from_iterable()은 반복 가능 객체의 반복자를 받아 모두 함께 결합되어 있습니다. 생성기를 생성하므로 추가 메모리를 사용하지 않습니다.

+0

감사! 나는 실제로 이것을 시도했지만, 나는 그것을 가져 오는 방법을 망쳤다는 것을 깨달았습니다. –

+0

@ Lord_Zane55 btw, 행렬이 반드시 "행의 시퀀스"는 아니지만 ... 행을 반환하는 "__getitem__"은 다소 재미 있습니다. 매우 직관적이지 않습니다. – Bharel

+0

반복을위한 snippet을 온라인에서 찾았습니다. 행렬이 "행 순서"가 아니며 나중에 __getitem__이 (가) 어떻게 사용해야하는지 설명 할 수 있습니까? –