【问题标题】:Access Rows and Columns in Python Matrix访问 Python 矩阵中的行和列
【发布时间】:2020-05-18 07:46:00
【问题描述】:
t = [[0],[1]]

如果矩阵实际上是一维的,我想要行和列的总和:

s1 = sum(t[0][:])
s2 = sum(t[:][0])

我得到了t[0][:]t[:][0] = 0,而这些应该是列表,第一行和第一列。

t[:][0] 应该是 == [0, 1]

如何正确获取总和以及列和行访问?

【问题讨论】:

  • t[:][0]t[0] 相同假设你有 t=[[0],[1],[2]] 然后是 t[:2] == [[0],[1]]
  • @ShubhamShaswat 谢谢,我怎样才能将列作为列表?

标签: python python-3.x list matrix multidimensional-array


【解决方案1】:

使用列表理解的解决方案:

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

sums_by_row = [sum(row) for row in matrix]

sums_by_col = [sum([row[icol] for row in matrix]) for icol in range(len(matrix[0]))]

print(sums_by_row)  # [6, 15, 24]

print(sums_by_col)  # [12, 15, 18]

【讨论】:

    【解决方案2】:

    你可以这样做,

    假设您的输入是:

    t=[[1,2,3],[4,5,6],[7,8,9]]
    
    
    #sum of row 
    [sum(x) for x in t]
    
    #sum of columns
    col_sum=[]
    row_length = len(t[0]) #row length 
    for idx in range(row_length):
      s=0
      for i in range(len(t)):
       s +=t[i][idx]
      col_sum.append(s)
    
    

    注意: t[:][0]t[0] 相同,假设您有 t=[[0],[1],[2]] 然后 t[:2] == [[0],[1]]

    【讨论】:

      【解决方案3】:

      你可以试试这个。

      >>> a=[[1,2,3],
         [4,5,6],
         [7,8,9]]
      >>> 
      >>> a
      [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      >>> def row_sum(_list,row_idx):
          return sum(_list[row_idx])
      
      >>> row_sum(a,0)
      6   #summation of 1st row i.e 1+2+3
      >>> def col_sum(_list,col_idx):
          cols=list(zip(*_list))
          return sum(cols[col_idx])
      
      >>> col_sum(a,0)
      12 #summation of 1st column i.e 1+4+7
      >>> col_sum(a,1)
      15 #summation of 2nd column i.e 2+5+8
      

      这是一个 numpy 方法。

      import numpy as np
      a=[[1,2,3],
             [4,5,6],
             [7,8,9]]
      a=np.array(a)
      def nprow_sum(_list,row_idx):
          return sum(_list[row_idx])
      def npcol_sum(_list,col_idx):
          return sum(_list[:,col_idx])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 2019-03-21
        • 2013-01-17
        • 1970-01-01
        相关资源
        最近更新 更多