我希望将以下字典转换为矩阵,其中字典的第一个和第二个值是列和行值。在矩阵为真的情况下,我希望有一个'1',当它是假的时我想要一个'0'。
{0:[2,5],1:[6,7.0],2:[6,8.0],3:[5,6.0],4:[1,5.0],5:[3,4.0] ],6:[4,5.0]}
所需的输出看起来像这样
1 2 3 4 5 6 7 8
1 0 0 0 0 1 0 0 0
2 0 0 0 0 1 0 0 0
3 0 0 0 1 0 0 0 0
4 0 0 1 0 1 0 0 0
5 1 1 0 1 0 1 0 0
6 0 0 0 0 1 0 1 1
7 0 0 0 0 0 1 0 0
8 0 0 0 0 0 1 0 0
谢谢堆,任何指针都会很棒!
丹尼尔。
答案 0 :(得分:2)
这是一个与你想要的输出匹配的,虽然我认为使用@ Antimony的答案作为基础(numpy)可能是要走的路(至少比这个答案更多)
N = 8
d = {0: [2, 5.0], 1: [6, 7.0], 2: [6, 8.0], 3: [5, 6.0], 4: [1, 5.0], 5: [3, 4.0], 6: [4, 5.0]}
m = [0] * (N ** 2 + 1)
for x, y in d.values():
m[x + int(y - 1) * N] = 1
m[int(y) + (x - 1) * N] = 1
print " ".ljust(9),
print " ".join(map(str, range(1, N + 1)))
print
for i in range(1, N ** 2 + 1):
if i % N == 1:
print "%d ".ljust(10) % (i / N + 1),
val = m[i]
print "%d " % val,
if not i % N:
print
<强>输出强>
1 2 3 4 5 6 7 8
1 0 0 0 0 1 0 0 0
2 0 0 0 0 1 0 0 0
3 0 0 0 1 0 0 0 0
4 0 0 1 0 1 0 0 0
5 1 1 0 1 0 1 0 0
6 0 0 0 0 1 0 1 1
7 0 0 0 0 0 1 0 0
8 0 0 0 0 0 1 0 0
根据@ DSM对@ Antimony回答的评论,这里有一个使用numpy:
import numpy
N = 8
m = numpy.zeros((N,N))
d = {0: [2, 5.0], 1: [6, 7.0], 2: [6, 8.0], 3: [5, 6.0], 4: [1, 5.0], 5: [3, 4.0], 6: [4, 5.0]}
for i,j in d.itervalues():
m[i-1,j-1] = 1
m[j-1,i-1] = 1
print " ".ljust(9),
print " ".join(map(str, range(1, N + 1)))
print
for i, line in enumerate(m.tolist()):
print "%s %s" % (("%s".ljust(10) % (i+1)," ".join(map(str, map(int, line)))))
<强>输出强>
1 2 3 4 5 6 7 8
1 0 0 0 0 1 0 0 0
2 0 0 0 0 1 0 0 0
3 0 0 0 1 0 0 0 0
4 0 0 1 0 1 0 0 0
5 1 1 0 1 0 1 0 0
6 0 0 0 0 1 0 1 1
7 0 0 0 0 0 1 0 0
8 0 0 0 0 0 1 0 0
答案 1 :(得分:0)
你给定的所需输出没有任何意义,但这里的东西可以做我猜你真正想要的东西。您可以通过执行m = m[1:,1:]
>>> d = {0: [2, 5.0], 1: [6, 7.0], 2: [6, 8.0], 3: [5, 6.0], 4: [1, 5.0], 5: [3, 4.0], 6: [4, 5.0]}
>>> dims = [1 + int(x) for x in map(max, zip(*d.values()))]
>>> m = numpy.zeros(dims, dtype=int)
>>> for v in map(tuple, d.values()):
m[v] = 1
>>> m
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 1]])
答案 2 :(得分:0)
使用数字作为字典键没有任何意义。你应该只使用一个列表。
vals = [True, True, False, True] # Assuming this is a list of n*n elements
matrix = [] # This will be a two-dimensional array, or matrix.
这将为任意大小的列表生成一个方阵:
from math import sqrt
size = sqrt(len(vals))
for x in range(0, size):
matrix.append(list(vals[x*size:x*size+size]))
# matrix == [[True, True], [False, True]]
# matrix[0][0] == True
# int(matrix[0][0]) == 1