简体   繁体   English

如何在Python中迭代2D矩阵?

[英]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] 通过错误的方式进行迭代,我的意思是,它首先向我显示了matrixRC[0][0]的值, matrixRC[0][0]向我显示了matrixRC[0][1]等,但是我希望它先显示matrixRC[0][0]然后再显示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] . 或者,如果它已经显示了matrixRC[0][0]然后显示了matrixRC[1][0]那么我希望它显示出matrixRC[0][0]然后显示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). 我真的很难想象此迭代代码的工作方式(我复制的代码的少数部分之一)。

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

This should work: 这应该工作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM