【问题标题】:How to make a nice matrix from a dictionary如何从字典中制作一个漂亮的矩阵
【发布时间】:2013-01-03 12:46:44
【问题描述】:

我想制作一个矩阵来制作嵌套字典的列表。 但是我不知道如何制作一个矩阵,更不用说如何将我的值放入其中。

我的字典看起来像:

    {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

它应该在一个矩阵中排序,所以它看起来像这样:

        1  2  3  4   5   6
     1  -  1  0  0   1   29
     2  13 -  1  0   21  0
     3  0  0  -  1   0   1
     4  1  17 1  -   2   0
     5  39 1  0  0   -   14
     6  0  0  43 1   0   -

我只是想了解如何制作矩阵:

    table=[[for 0 in range(6)] for j in range[6]]
    print table
    for d1 in range(6):
        for d2 in range(6):
            table[d1][d2]=d1+d2+2
    print table

但我有一本字典,而不是列表。我真的迷路了。

【问题讨论】:

  • 向我们展示您迄今为止所做的努力,我们会看到可以提供帮助的地方。
  • 这是一个开始:print ' '.join(' ' + str(c) for c in range(1,7))
  • 我已经尽力制作一个矩阵作为答案

标签: python dictionary matrix


【解决方案1】:

importpandasas pd

a = pd.DataFrame({'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
                  '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
                  '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
                  '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
                  '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
                  '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}})

输入a:

    1   2   3   4   5   6
1 NaN  13   0   1  39   0
2   1 NaN   0  17   1   0
3   0   1 NaN   1   0  43
4   0   0   1 NaN   0   1
5   1  21   0   2 NaN   0
6  29   0   1   0  14 NaN

然后可以打印成您的格式:

print a.to_string(na_rep='-')

印刷:

    1   2   3  4   5   6
1   -   1   0  0   1  29
2  13   -   1  0  21   0
3   0   0   -  1   0   1
4   1  17   1  -   2   0
5  39   1   0  0   -  14
6   0   0  43  1   0   -

【讨论】:

  • 谢谢。但我应该创建一个名为 def prittyPrint 的函数,它将字典作为参数。
【解决方案2】:

使用str.format():

dic = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

strs = "{0:^2} {1:^2} {2:^2} {3:^2} {4:^2} {5:^2} {6:^2}"    

print strs.format(" ", *sorted(dic))

for x in sorted(dic):
    print strs.format(x, *(dic[x].get(y, '-') for y in sorted(dic)))

输出:

   1  2  3  4  5  6 
1  -  1  0  0  1  29
2  13 -  1  0  21 0 
3  0  0  -  1  0  1 
4  1  17 1  -  2  0 
5  39 1  0  0  -  14
6  0  0  43 1  0  - 

您也可以像这样生成strs

strs = " ".join("{"+"{0}{1}".format(i, ":^2}") for i in range(7))  

【讨论】:

    【解决方案3】:

    这对我有用。它不是很pythonic,因为我不使用列表推导和那种东西,但这种方式更容易阅读和理解:

    import sys
    
    matrix = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
              '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
              '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
              '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
              '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
              '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}
    
    #print the column index
    sys.stdout.write ("\t") # empty tab at the beginning
    for col_index in range (1, len(matrix)+1):
        sys.stdout.write ("%d\t" % col_index)
    print ""
    
    # order the matrix rows, using the dictionary keys
    for row_index in sorted (matrix.iterkeys()):
        #print the row index
        sys.stdout.write (str(row_index)+"\t")
    
        # take each row, and order it by its inner key:
        row = matrix[row_index]
        ordered_row = sorted (row.iterkeys())
    
        # iterate from 1 to number_of_matrix_rows
        for col_index in range (1, len(matrix)+1):
            # if the current column exists as a key in
            # the row, print it. Otherwise, print "-"
            row_item = "-"
            if str(col_index) in ordered_row:
                row_item = row[str(col_index)]
            sys.stdout.write (str(row_item)+"\t")
    
        # print next row
        print ""
    

    【讨论】:

      【解决方案4】:

      这是在屏幕上打印矩阵的 python 代码。致电prettyPrint(data)

      table 是一个包含数据的多维数组(矩阵)。

      import string
      
      data = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
          '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
          '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
          '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
          '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
          '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}
      
      def prettyPrint(data):
          count = len(data)
      
          table = [[0 for x in xrange(count)] for x in xrange(count)]
      
          print string.ljust(' ', 4),
          for j in range(1, count + 1):
              print string.ljust(`j`, 4),
          print ""
      
          for i in range(1, count + 1):
              print string.ljust(`i`, 4),
      
              for j in range(1, count + 1):
                  #print string.rjust(`j`, 4),
                  if j != i:
                      print string.ljust(`data[str(i)][str(j)]`, 4),
                      table[i-1][j-1] = data[str(i)][str(j)]
                  else:S
                      print string.ljust('-', 4),
                      table[i-1][j-1] = '-'
              print ""
      
          print "\nMatrix: \n"
          for row in table:
              print row
      
      prettyPrint(data)
      

      输出:

      >>> 
           1    2    3    4    5    6    
      1    -    1    0    0    1    29   
      2    13   -    1    0    21   0    
      3    0    0    -    1    0    1    
      4    1    17   1    -    2    0    
      5    39   1    0    0    -    14   
      6    0    0    43   1    0    -    
      
      Matrix: 
      
      [0, 1, 0, 0, 1, 29]
      [13, 0, 1, 0, 21, 0]
      [0, 0, 0, 1, 0, 1]
      [1, 17, 1, 0, 2, 0]
      [39, 1, 0, 0, 0, 14]
      [0, 0, 43, 1, 0, 0]
      >>> 
      

      【讨论】:

      • 。非常感谢您。我需要我订购的表格来找到重叠最少的序列,它是 LONG 练习的一部分。
      • 更新的答案,表格是你的矩阵......有'0'而不是'-'。
      • 我希望它是'-',而不是'0'。表中1-6的所有数字和左侧都是序列的数字。从矩阵中我可以看到,如果序列 4 是左序列,则序列 4 的只有 0 或 1 个字母与任何其他序列重叠(所有重叠在彼此的末尾。第一个序列的右端与第二个序列的左端重叠序列等等。)所以从表中我可以看到序列应该是 4-2-5-1-6-3,然后我需要将它们链接在一起。
      • @anne 我不明白你的链接问题,你能解释一下吗?
      • 矩阵顶部1-6的数字,左侧1-6的数字,序列是键。它们代表字母序列。序列可以相互重叠,但最后总是重叠(一个的左端与下一个的右端)。因为第 4 列中的数字
      【解决方案5】:

      一个基于@Ashwini Chaudhary 使用str.format 的解决方案的函数,它可以采用可变长度的字典:

      def prettyPrint(d,space=5,fill='-'):
          strs = ''.join('{{{0}:^{1}}}'.format(str(i),str(space)) 
                                       for i in xrange(len(d)+1))
          std = sorted(d)
          print strs.format(" ",*std)
          for x in std:
              print strs.format(x,*(d[x].get(y,fill) for y in std)) 
      
      prettyPrint(d)
      

      输出:

             1    2    3    4    5    6  
        1    -    1    0    0    1   29  
        2   13    -    1    0   21    0  
        3    0    0    -    1    0    1  
        4    1   17    1    -    2    0  
        5   39    1    0    0    -   14  
        6    0    0   43    1    0    - 
      

      或者:

      prettyPrint(d,space=3,fill='0')
      

      输出:

          1  2  3  4  5  6 
       1  0  1  0  0  1 29 
       2 13  0  1  0 21  0 
       3  0  0  0  1  0  1 
       4  1 17  1  0  2  0 
       5 39  1  0  0  0 14 
       6  0  0 43  1  0  0
      

      【讨论】:

        【解决方案6】:

        可能不是一个完美或最有效的解决方案,但它确实有效:

        def printMatrix (d):
            # get the amount of characters needed for the maximum number
            numberWidth = len(str(max(max(v.values()) for v in d.values())))
        
            # function to format the numbers
            formatNumber = lambda x: str(x).rjust(numberWidth)
        
            keys = sorted(d.keys())
            rows = [' '.join(map(formatNumber, [''] + keys))]
        
            for r in keys:
                row = [r]
                for k in keys:
                    row.append(d[r].get(k, '-'))
                rows.append(' '.join(map(formatNumber, row)))
        
            print('\n'.join(rows))
        

        这样使用:

        >>> d = { ... }
        >>> printMatrix(d)
              1   2   3   4   5   6
          1   -   1   0   0   1  29
          2  13   -   1   0  21   0
          3   0   0   -   1   0   1
          4   1  17   1   -   2   0
          5  39   1   0   0   -  14
          6   0   0  43   1   0   -
        

        【讨论】:

          【解决方案7】:

          以下单行可以将您的字典更改为列表列表(方阵):

          [[d[str(i)].get(str(j), '-') for j in range(1, 7)] for i in range(1, 7)]
          

          d 是您的输入字典。基于此,您可以轻松地以您想要的任何格式进行打印。顺便说一句,除非这是一项学校作业,否则我认为以任何具体格式打印都不重要。将字典更改为类似矩阵的数据结构更有意义。如果只是为了调试,您可以使用pprint 来获得更好的输出。

          【讨论】:

          • 谢谢。任务是让它更具可读性,而矩阵可以做到这一点。
          【解决方案8】:

          这是一个没有外部库的冗长而灵活的代码,它还返回一个可用的矩阵。

          dict_matrix = {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
                         '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
                         '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
                         '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
                         '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
                         '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}
          
          def matricize_dict(a_dict, x_size, y_size):
              matrix = []
          
              for i in range(y_size):
                  line = []
                  for j in range(x_size):
                      line.append('-')
                  matrix.append(line)
          
              for i in range(y_size):
                  line = dict_matrix[str(i+1)]
                  for j in range(x_size):
                      try:
                          cell = line[str(j+1)]
                      except KeyError:
                          pass
                      else:
                          matrix[i][j] = cell
              for item in matrix:
                  print(item)
          
              return matrix
          
          matricize_dict(dict_matrix, 6, 6)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-11-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-06-19
            • 2015-10-25
            相关资源
            最近更新 更多