簡體   English   中英

有沒有更好的方法來編寫這個嵌套的 for 循環?

[英]Is there a better way to write this nested for loop?

我正在嘗試編寫一個 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)

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

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

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

如果是 numpy 數組,則可以更改行的順序並轉置:

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

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM