【问题标题】:Is there a better way to write this nested for loop?有没有更好的方法来编写这个嵌套的 for 循环?
【发布时间】:2022-01-10 20:09:24
【问题描述】:

我正在尝试编写一个 for 循环,该循环采用 2D 矩阵的内容并将它们旋转 90 度以进行写入,如下所示:

|2|3|4|5|
---------
|7|6|8|9|

to:

|7|2|
-----
|6|3|
-----
|8|4|
-----
|9|5|

my code so far is:

rotated = []

#you may change matrix as you want
matrix=[[1 , 2 , 3] ,[ 4 , 5 , 6]]

# append a new matrix for each col      
for i in range(len(matrix[0])):
    rotated.append([])
    # append the last up till the 1st item to the 1st list in our new rotated list
    for j in range(len(matrix) - 1, -1, -1):
        rotated[i].append(matrix[j][i])
print(rotated)

【问题讨论】:

  • 只要用zip()list(zip(*reversed(l)))给你[(7, 2), (6, 3), (8, 4), (9, 5)]
  • 在最后一行...你应该使用旋转或定义旋转来使代码运行

标签: python for-loop multidimensional-array


【解决方案1】:

这可能是作弊,但是..它有效;)

arr = [
    [2, 3, 4, 5],
    [7, 6, 8, 9]
]

rotated = [ list(values) for values in zip(*reversed(arr)) ]
print(rotated)

【讨论】:

    【解决方案2】:

    如果是numpy数组,可以改变行的顺序并转置:

    arr = np.array([[2,3,4,5],[7,6,8,9]])
    arr[[1,0]].T
    

    输出:

    [[7 2]
     [6 3]
     [8 4]
     [9 5]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2019-06-15
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多