【问题标题】:Get each column in a 3x4 matrix in python在python中获取3x4矩阵中的每一列
【发布时间】:2020-03-18 03:14:20
【问题描述】:

所以我是 python 的绝对新手,我无法理解如何准确地遍历 2D 数组来获取列。

我有一个看起来像这样的 3x4 矩阵:

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

我在 python 上尝试过的代码如下所示:

def get_column(row, row1, row2):
    get_total = 0
    # i = 0
    # j = 0
    # row = list()
    # end = " "
    m = []
    col_count = 0
    # i is the number of lists in the super list
    # so we need go two_dim[i]
    two_dim = [[row], [row1], [row2]]
    for i in range(len(two_dim)):
        print(two_dim[i])
        for j in range(len(two_dim[i])):
            print(two_dim[i][j])
            for k in range(len(two_dim[j])):

                first_column = two_dim[i][j]
                # print(first_column, end=" ")
                col_count += 1
    # print(two_dim[i][j][2])
    # print(second_column, end=" ")
    # second_column = row1[j][j+1]
    # third_column = row2[k][k+2]

我已经绞尽脑汁想弄清楚我究竟如何能够遍历矩阵来获得列。

我只能获取第一列,但无法打印其他 3 列中的任何一个。

如果有人能指引我正确的方向,我将不胜感激!

编辑:忘了提,我想以编程方式进行,而不是使用库。但如果它不可行,那么库就可以工作!

非常感谢!

【问题讨论】:

标签: python matrix multidimensional-array


【解决方案1】:

使用Pandas 来实现您的结果。

import pandas as pd
df = pd.DataFrame([[2, 3, 4, 5], [6, 7, 8, 9], [2, 4, 5, 6]])
for col in df.columns:
  print list(df[col])

#Output
[2, 6, 2]
[3, 7, 4]
[4, 8, 5]
[5, 9, 6]

或者,您可以使用@wwii 解决方案 -

zip(*list_of_lists)

【讨论】:

  • 您好,感谢您的回复,有什么方法可以通过编程而不是使用 pandas 来实现?
  • 可以使用cmets中提供的@wwii解决方案
【解决方案2】:

使用两个 for 循环或列表理解

a = [[2, 3, 4, 5], [6, 7, 8, 9], [2, 4, 5, 6]]
transpose_a = [[a[column][row]for column in range(len(a))]for row in range(len(a[0]))]
for col in transpose_a:
    print(col)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2013-07-31
    • 2017-08-14
    • 2013-03-17
    • 2016-07-09
    • 2019-01-27
    相关资源
    最近更新 更多