我有一個顯示關節之間連接的陣列,
如下所示:
[
("Pelvis","Torso"),
("Torso","Head"),
("Torso","Biscep.L"),
("Biscep.L","Forearm.L"),
("Forearm.L","Hand.L"),
("Pelvis","")
("Pelvis","Thigh.L"),
("Thigh.L","Shin.L"),
("Shin.L","Heel.L"),
("Heel.L","Toe.L"),
("Torso","Biscep.R"),
("Biscep.R","Forearm.R"),
("Forearm.R","Hand.R"),
("Pelvis","Thigh.R"),
("Thigh.R","Shin.R"),
("Shin.R","Heel.R"),
("Heel.R","Toe.R"),
]
我正在嘗試對其進行排序,以使這些值不重復并且像這樣放置在另一個中:
{
"Pelvis":{
"Torso":{
"Biscep.L":{
"Forearm.L":{
"Hand.L":{}
}
},
"Head":{},
"Thigh.L":{},
},
...
}
我如何實作這一目標?
uj5u.com熱心網友回復:
這可以作為圖形問題來處理。我會用
假設L輸入,您可以使用 構建它networkx.from_edgelist,然后connected_components在第一個上找到 and 回圈all_simple_edge_paths(假設您沒有分支):
import networkx as nx
# build directed graph
G = nx.from_edgelist((t for t in L if t[0] and t[1]), # drop empty strings
create_using=nx.DiGraph)
# to find roots and leafs
IN = G.in_degree()
OUT = G.out_degree()
# complete dictionary
out = {}
for sub in nx.weakly_connected_components(G):
root = next(n for n in sub if IN[n] == 0) # get root
leafs = [n for n in sub if OUT[n] == 0] # get leafs
for path in nx.all_simple_edge_paths(G, root, leafs):
d = out
for parent, child in path:
d.setdefault(parent, {child: {}})
d = d[parent]
d.setdefault(child, {})
輸出字典(out):
{'Pelvis': {'Thigh.L': {'Shin.L': {'Heel.L': {'Toe.L': {}}}},
'Thigh.R': {'Shin.R': {'Heel.R': {'Toe.R': {}}}},
'Torso': {'Biscep.L': {'Forearm.L': {'Hand.L': {}}},
'Biscep.R': {'Forearm.R': {'Hand.R': {}}},
'Head': {}}}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510102.html
標籤:Python算法排序字典
