我甚至不知道如何描述這一點,但我希望有人能夠理解和幫助。我公司擁有一批名單是由的路徑可能出現在導航結構中的節點,例如:返回路徑中的所有項目,包括遍歷每個級別的兄弟姐妹
['nav1']
['nav1','subnav1']
['nav1','subnav2']
['nav2']
['nav3']
['nav3','subnav1']
['nav3','subnav2']
['nav3','subnav3']
['nav3','subnav3','subsubnav1'] **
['nav3','subnav3','subsubnav1','subsubsubnav']
['nav4']
['nav5']
['nav5','subnav1']
['nav5','subnav1','subsubnav1']
['nav5','subnav2']
['nav5','subnav3']
假如我選擇在這個導航由**指示的節點,我也想返回所有作爲父節點和本節點的兄弟節點。 (如Windows資源管理器樹形菜單)。
因此,使用所選擇的例子,我將返回:
['nav1']
['nav2']
['nav3']
['nav3','subnav1']
['nav3','subnav2']
['nav3','subnav3']
['nav3','subnav3','subsubitem1']
['nav3','subnav3','subsubitem1','subsubsub']
['nav4']
['nav5']
我想以最有效的Python的方式來實現這一目標。我自己做了幾次嘗試,但都沒有成功。這是我最近來的,但不幸的是它不會返回兄弟姐妹。
#model_path is the current selected node e.g ** as illustrated above
#always show 1st level nodes
if len(node_path) == 1:
return True
#always show final level nodes
if model_path == node_path[:-1]:
return True
#show all items in tree from root to model
if len(node_path) > 1:
return self._find_sublist(node_path, model_path) >= 0
#show siblings at each level traversed
#????
# find_sublist credit to this post by nosklo:
# http://stackoverflow.com/a/2251638/1844977
def _find_sublist(self, sub, bigger):
if not bigger:
return -1
if not sub:
return 0
first, rest = sub[0], sub[1:]
pos = 0
try:
while True:
pos = bigger.index(first, pos) + 1
if not rest or bigger[pos:pos+len(rest)] == rest:
return pos
except ValueError:
return -1
我真的很感謝這裏的一些幫助,因爲我一直在努力尋找解決方案。我應該補充一個解決方案,那就是在無限數量的層次上工作。
如果這個問題不清楚,或者它是重複的(我擔心它可能),我表示歉意,但是我並不真正知道我所要求的正確術語並不能幫助我搜索。
順便提一下,我僅限於Python 2.4。
你可以只要求「完整路徑」再次你到達的對象,然後用路徑斜槓「/」分開,然後遍歷字典來構建結構。 – 2013-03-11 22:08:17