什麼是在Python中用相當低的運行時查找第一個匹配路徑的有效方法?Pythonic方法:用最少的運行時間找到第一個匹配路徑
例如,
我作爲輸入的路徑:
test1/testA/testB
和一組可以匹配路徑(在我的使用情況下,這將是在千元)。
test1/testB
test1/testA
testC/testD
不會有像下面任何重疊的路徑和只能被匹配到一個路徑:
test1/testA
test1/testA/testB
在上面的例子中,由於是test1/testA/testB
在test1/testA
,我想返回test1/testA
。
我的方法是構建一個內存樹並在樹中標記每個節點(如果它是端點的話)。然後,我會每次遍歷樹來查找路徑是否可以匹配。不幸的是,這需要一點點工作。
是否有一個Python函數或庫很容易完成這個工作?或者我需要從頭開始寫這個?
你能解釋一下你試圖解決的問題嗎?可能有比你想要的更好的方法。 – 2014-10-02 17:03:00
當你說「沒有重疊的路徑」時,你的意思是所有的終端都是唯一的嗎? – theodox 2014-10-02 17:03:51
我試圖解決一個問題,我有一個文件路徑,我需要它來自的項目。我有一個項目名稱及其相關路徑的列表。但是,文件路徑可能不一定與項目路徑直接匹配,但可能駐留在項目路徑中。我可能會每秒多次調用此函數,並且可能會有數千個項目路徑。 – Andy 2014-10-02 17:10:31