我取了一个图的邻接矩阵,然后将其转换为一个 sympy 矩阵。这是我的代码:
import networkx as nx
import sympy as sp
import matplotlib.pyplot as plt
G = nx.Graph()
E = [[1,2], [1,3], [2,4], [4,1]]
G.add_edges_from(E)
nx.draw_networkx(G)
A = nx.adjacency_matrix(G).todense()
m = sp.Matrix(A)
print((m.table(sp.StrPrinter())))
我得到了什么:
Output:
[ 0.0, 1.00000000000000, 1.00000000000000, 1.00000000000000]
[1.00000000000000, 0.0, 0.0, 1.00000000000000]
[1.00000000000000, 0.0, 0.0, 0.0]
[1.00000000000000, 1.00000000000000, 0.0, 0.0]
发生了什么,我如何将所有这些值转换为整数?我想我可以做一个循环并用 int(i)
将它们全部转换,但必须有一个更短的版本。一个朋友运行相同的代码,他的值从一开始就是整数
答案 0 :(得分:0)
我认为这是因为您的矩阵类型是浮动的(64 位或 32 位)。要使其 ints
,您可以像这样使用 dtype
参数:
>>> m = sp.Matrix(A, dtype=int)
>>> m
Matrix([
[0, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 0],
[1, 1, 0, 0]])