为什么 networkx list(g.edges) 不是 return int?

Why networkx list(g.edges) does not return int?

pair = list(g.edges()) print(pair)

为什么第二个节点的结果不是'int'? result

我使用firstnode = pair[a][0]secondnode = int(pair[a][1]将第二个节点的数字从浮点数转换为整数。 但是我仍然很困惑为什么它是浮动的?

所以我不完全确定你的代码是什么样的,但是因为你在你的图表中的所有边缘都有一个浮点数作为第二个数字并且你想将它输入为整数,我建议你这样做:

我的代码示例:

import networkx as nx

# Create dummy graph
g = nx.Graph()
g.add_edge(1,2.0)
g.add_edge(5,4.3)
g.add_edge(8,3.9)

# Get list of all edges
pair = list(g.edges())
print(pair)

# Iterate through all edges
for a in range(len(g.edges())):
  # Get first node of edge
  firstnode = pair[a][0]
  # Get second node of edge and type cast it to int
  secondnode = int(pair[a][1])
  # Print nodes / or execute something else here
  print(firstnode,secondnode)
  print()

这是输出:

[(1, 2.0), (5, 4.3), (8, 3.9)]
1 2

5 4

8 3

希望对您有所帮助!

我有同样的问题 - 描述我的情况 - 如果我打印我的节点边缘:

for edge in G.edges():
  print(edge)

给出:

('1', '11')
('1', '6')
('2', '2')
...etc

意味着节点 ID 是 STRINGS 而不是 INT。例如,您需要:

print("Node {} has degree {}".format(node_id, G.degree[node_id]))
print("Node {} has degree {}".format('1', G.degree['i']))