【问题标题】:creation of a N-dimensional matrix with a dictionary - python 2.7使用字典创建 N 维矩阵 - python 2.7
【发布时间】:2015-06-17 08:17:40
【问题描述】:

我想知道如何创建 N 大小的矩阵,其中矩阵的索引将是字典中的键。 我假设python至少可以选择支持这个矩阵,以防每个键的值是逻辑无符号整数(或掩码为一个)我将可以访问矩阵中的任何单元格 通过使用 dict[key] 而不是索引。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    以下示例应该会有所帮助,它会创建一个大小为 2 × 3 的二维矩阵:

    d = {
        0: {0: 'a', 1: 'b', 2: 'c'},
        1: {0: 'd', 1: 'e', 2: 'f'},
    }
    from pprint import pprint
    pprint(d)
    
    # Using keys as indices
    print d[1][2]
    
    # output
    {0: {0: 'a', 1: 'b', 2: 'c'}, 1: {0: 'd', 1: 'e', 2: 'f'}}
    f
    

    【讨论】:

      【解决方案2】:

      我会怎么做:

      def showMatrixForm(matrix):
          matshape=""
          for row in range(1,matrix["rows"]+1):
              for column in range(1,matrix["columns"]+1):
                  spaces=5-len(str(matrix[str(row)+","+str(column)]))
                  matshape+="".join([" " for space in range(spaces)])+str(matrix[str(row)+","+str(column)])
              matshape+="\n"
          return matshape
      
      
      
      matrix={}
      
      rows=10
      columns=10
      
      matrix["rows"]=rows
      matrix["columns"]=columns
      
      i=0
      for row in range(1,rows+1):
          for column in range(1,columns+1):
              i+=1
              matrix[str(row)+","+str(column)]=i
      
      print(showMatrixForm(matrix))
      '''
          1    2    3    4    5    6    7    8    9   10
         11   12   13   14   15   16   17   18   19   20
         21   22   23   24   25   26   27   28   29   30
         31   32   33   34   35   36   37   38   39   40
         41   42   43   44   45   46   47   48   49   50
         51   52   53   54   55   56   57   58   59   60
         61   62   63   64   65   66   67   68   69   70
         71   72   73   74   75   76   77   78   79   80
         81   82   83   84   85   86   87   88   89   90
         91   92   93   94   95   96   97   98   99  100
      '''
      
      print(matrix["1,2"],matrix["8,4"],matrix["5,7"])
      '''
      (2, 74, 47)
      '''
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-30
        • 2016-05-27
        • 2014-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多