10

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

我的字典看起来像:

    {'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

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

4

8 回答 8

16

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   -
于 2013-01-03T12:56:33.427 回答
5

使用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))  
于 2013-01-03T13:27:30.443 回答
2

一个基于@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
于 2013-01-03T14:08:59.123 回答
2

这是将在屏幕上打印矩阵的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]
>>> 
于 2013-01-03T13:14:17.217 回答
2

这对我有用。它不是很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 ""
于 2013-01-03T13:17:44.233 回答
1

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

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   -
于 2013-01-03T13:15:37.023 回答
1

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

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

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

于 2013-01-03T13:32:54.563 回答
0

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

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)
于 2013-01-03T13:28:27.267 回答