What is the method for transposing a two-dimensional array in Python?

You can use the zip function to transpose a 2D array. The specific method is as follows:

# 定义一个二维数组
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

# 使用zip函数进行转置
transpose_matrix = list(map(list, zip(*matrix)))

# 输出转置后的二维数组
for row in transpose_matrix:
    print(row)

Running the above code will result in:

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

With the above methods, it is possible to achieve the transpose operation of a two-dimensional array.

bannerAds