sur*_*uri 5 python graph networkx
我正在尝试打印图形的连接组件.但它印刷的是发电机的对象.
这是我的graph.py
import networkx as nx
import matplotlib.pyplot as plt
#import math
import csv
#import random as rand
import sys
def buildG(G, file_, delimiter_):
#construct the weighted version of the contact graph from cgraph.dat file
reader = csv.reader(open(file_), delimiter=delimiter_)
for line in reader:
if float(line[2]) != 0.0:
G.add_edge(int(line[0]),int(line[1]),weight=float(line[2]))
def main():
graph_fn="tempset3.txt";
G = nx.Graph() #let's create the graph first
buildG(G, graph_fn, ',')
print G.nodes()
print G.number_of_nodes()
#nx.draw(G)
#plt.show(G)
n = G.number_of_nodes()
print ("no of nodes: ", n)
comps=nx.connected_components(G)
print comps
main()
Run Code Online (Sandbox Code Playgroud)
这是我的tempset3.txt
0,1,9
1,3,5
1,4,17824
2,5,1199
2,6,729
5,7,619
5,8,241
5,10,227
7,8,4
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它给出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 10]
10
('no of nodes: ', 10)
<generator object connected_components at 0x360f140>
Run Code Online (Sandbox Code Playgroud)
如何正确打印连接的组件?
输出应为:[[0,1,3,4],[2,5,6,7,8,10]]
只需list
在generator
对象上使用print (list(comps))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 10]
10
no of nodes: 10
[[0, 1, 3, 4], [2, 5, 6, 7, 8, 10]]
Run Code Online (Sandbox Code Playgroud)
或者迭代生成器对象:
for comp in comps:
print (comp)
[0, 1, 3, 4]
[2, 5, 6, 7, 8, 10]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3664 次 |
最近记录: |