Brendan Mesters
Brendan Mesters

Reputation: 211

How to iterate over a 2D matrix in Python?

I'm having trouble wrapping my head around how to set up iteration code, I build a matrix as a list of lists

for _ in range(rowsLen):
    self.matrixRC.append([2 for _ in range(collsLen)])

With the iteration code that I have at this moment it iterates in the wrong way.

def __iter__(self): 
    for i in self.matrixRC:
        for j in i:
            yield j


def __next__(self): 
    for i in self.matrixRC:
        for j in i:
            return j

By iterating in the wrong way I mean that it first shows me the values of matrixRC[0][0] then matrixRC[0][1] etc., but I want it to show matrixRC[0][0] then matrixRC[1][0]

Or if it already shows matrixRC[0][0] then matrixRC[1][0] then I would like it to show matrixRC[0][0] then matrixRC[0][1]. I'm really having trouble visualizing how this iteration code works (one of the few parts of code that I have copied).

Upvotes: 0

Views: 958

Answers (2)

Reut Sharabani
Reut Sharabani

Reputation: 31339

This should work:

def __iter__(self): 
       yield from chain.from_iterable(zip(*(self.matrixRC or [])))

def __next__(self):
    return next(iter(self))

Upvotes: 1

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

def __iter__(self): 
       for i in zip(*self.matrixRC):
            for j in i:
                yield j

    def __next__(self): 
        for i in zip(*self.matrixRC):
            for j in i:
                return j

Upvotes: 2

Related Questions