Rotating a two-dimensional array in Python

后端 未结 7 1351
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 19:38

In a program I\'m writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job:

7条回答
  •  执念已碎
    2020-11-28 19:55

    Rotating Counter Clockwise ( standard column to row pivot ) As List and Dict

    rows = [
      ['A', 'B', 'C', 'D'],
      [1,2,3,4],
      [1,2,3],
      [1,2],
      [1],
    ]
    
    pivot = []
    
    for row in rows:
      for column, cell in enumerate(row):
        if len(pivot) == column: pivot.append([])
        pivot[column].append(cell)
    
    print(rows)
    print(pivot)
    print(dict([(row[0], row[1:]) for row in pivot]))
    

    Produces:

    [['A', 'B', 'C', 'D'], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
    [['A', 1, 1, 1, 1], ['B', 2, 2, 2], ['C', 3, 3], ['D', 4]]
    {'A': [1, 1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3], 'D': [4]}
    

提交回复
热议问题