Search code examples
pythonpython-3.xzip

code equivalent in Python 3 for zip related statements


What would be the code equivalent for the following in Python 3?

def spiral_matrix(m):
    result = []
    while len(m) > 0:
        result += m[0]
        m = zip(*m[1:len(m)])[::-1]
    return result

the error is:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/mona/Python_Playground/spiral_matrix.py", line 38, in <module>
    print(spiral_matrix(b))
  File "/Users/mona/Python_Playground/spiral_matrix.py", line 34, in spiral_matrix
    m = zip(*m[1:len(m)])[::-1]

Solution

  • Try this:

    m = list(zip(*m[1:len(m)]))[::-1]
    

    In Python 3, zip() return an iterator. Wrapping it in list() will run the iterator to create list, giving the same behavior as Python 2.