简体   繁体   中英

Python: how to unpack more than one value in a for?

I'm trying to unpack two values in a for:

def getDiagonal(self):
    diagonal = [(r, c) for (r,c) in range(0, len(self.matrix)), range(0, len(self.matrix[0]))]
    return diagonal

And gives this error:

    Traceback (most recent call last):
  File "matrixModule.py", line 4, in <module>
    print m.getDiagonal()
  File "C:\Users\Capinzal\Google Drive\ProgramaþÒo\Matrix\matrix.py", line 46, in getDiagonal
    diagonal = [(r, c) for (r,c) in range(0, len(self.matrix)), range(0, len(self.matrix[0]))]
ValueError: too many values to unpack

With zip() :

diagonal = [(r, c) for (r,c) in zip(range(len(self.matrix)), range(len(self.matrix[0])))]

That said, if you just want the tuple anyway, there's no need to unpack it or even make a comprehension, although you would still need zip() :

diagonal = list(zip(range(len(self.matrix)), range(len(self.matrix[0]))))

You can also omit the 0 for the range object, as that's the default start value. You'd need it if you wanted to specify a custom step value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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