日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【Python学习系列二十五】数据结构-有向图绘制

發(fā)布時間:2025/4/16 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python学习系列二十五】数据结构-有向图绘制 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1、場景:從文件中讀取節(jié)點、有向邊,然后繪制。

2、參考代碼:

# -*- coding: utf-8 -*-import networkx as nx import matplotlib.pyplot as plt#讀取文件,獲取節(jié)點和邊 f = open("D:\\tmp\\gy_contest_link_top.txt", "r") nodelist=[] edgelist=[] while True: line = f.readline() if line: pass # do something here line=line.strip()node=line.split(';')[0]#獲取圖節(jié)點nodelist.append(node)in_nodes=line.split(';')[1].split('#')#獲取圖邊,該節(jié)點是終點for ins in range( len(in_nodes) ) :if in_nodes[ins].strip() !='': in_edge=(in_nodes[ins],node)if in_edge not in edgelist:edgelist.append(in_edge)out_nodes=line.split(';')[2].split('#')#獲取圖邊,該節(jié)點是起點 for ins in range( len(out_nodes) ) :if out_nodes[ins].strip() !='': out_edge=(node,out_nodes[ins])if out_edge not in edgelist:edgelist.append(out_edge)else: break f.close() del nodelist[0] #刪除表頭生成的節(jié)點 del edgelist[0] del edgelist[0] #刪除表頭生成的邊 #print len(nodelist) #圖節(jié)點 #print len(edgelist) #邊數(shù)#有向圖繪制 G=nx.DiGraph() G.add_nodes_from(nodelist) G.add_edges_from(edgelist) nx.draw_networkx(G, pos=None, arrows=True, with_labels=True) #plt.savefig('D:\\tmp\\it.png') plt.show()
效果圖:


筆者沒有對節(jié)點名做簡易處理,所以看起來有點亂。


總結

以上是生活随笔為你收集整理的【Python学习系列二十五】数据结构-有向图绘制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。