Python 遍历矩阵 class

Python iterating over matrix class

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__,我在迭代工作后这样做)

您可以像这样实施 __iter__()

from itertools import chain

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

itertools.chain.from_iterable() 接受可迭代的可迭代并将它们组合在一起。它创建一个生成器,因此不使用额外的内存。