[英]create a python Tree from a list of strings
我在 windows10 機器上使用最新版本的 python。 我有一份半卡車采用的 10 萬條路線的清單。 每條路線只有 1 個單站。 每條路線都起源於城市A,然后到達城市B。 它的結構與此類似:
list_single_stop_routes = [
'cityA to cityB',
'ohio to cali',
'penn to texas',
'cali to tenn',
'tenn to ohio']
我想做的是創建一個“擴展路線”列表,其中每條擴展路線都有一些從城市到城市的任意數量的站點。
我首先從每條路線獲取每個城市 A 的列表,並將其用作我的起始位置。 然后我取了相應的cityB,然后遍歷每條單站路線,其中我當前的cityB是新的路線cityA。 因此,假設我的出發地是俄亥俄州,那么 cityB 是印第安納州。 現在我想遍歷每條路線以找到印第安納州是始發地(cityA)的每條路線,我可能會找到一條寫着“印第安納州到德克薩斯州”的路線。 因此,到目前為止,我的結構會說“俄亥俄州到印第安納州到德克薩斯州”等等,直到(可能)不再建立聯系。
我嘗試創建字典和列表來幫助我構建輸出,但我似乎無法弄清楚究竟什么會起作用。 請記住,必須保持每條路線的正確順序。 然后我開始考慮某種數據結構,可能類似於樹? 最終我想要一個這樣的列表:
list_extended_routes = [
"ohio to cali to tenn to texas to flor to nevada to wisconsin to newyork",
"missou to texas to wisconsin to texas to ohio",]
希望有人可以幫助我朝着正確的方向前進? 謝謝!
這本質上是一個圖形問題,因此最好使用諸如networkx
類的圖形庫。
圖表如下:
您可以使用以下方法構建它:
list_single_stop_routes = [
'cityA to cityB',
'ohio to cali',
'penn to texas',
'cali to tenn',
'tenn to ohio',
'ohio to indiana'
]
import networkx as nx
G = nx.from_edgelist(s.split(' to ') for s in list_single_stop_routes)
然后很容易找到2個城市(節點)之間的所有路線(路徑):
list(nx.all_simple_paths(G, source='indiana', target='tenn'))
輸出:
[['indiana', 'ohio', 'cali', 'tenn'], ['indiana', 'ohio', 'tenn']]
如果你想要一個有向圖,使用
G = nx.from_edgelist((s.split(' to ') for s in list_single_stop_routes),
create_using=nx.DiGraph)
現在沒有從印第安納州到田納西州的路線
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.