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は、可変長のdictを取ることができます:

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 に答える
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 に答える
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 に答える
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 に答える