我有一本包含 2 個串列的字典。
{'depth': [0, 1, 1, 2, 3, 3, 3, 1, 1, 2, 3], 'nodeName': ['root', 'Deleted Customers', 'New Customers', 'Region', 'Europe', 'Asia', 'America', 'Deleted Partners', 'New Partners', 'Region', 'Europe']}
我需要根據python中的串列構建完整路徑。
root\Deleted Customers
root\New Customers\Region\Europe
root\New Customers\Region\Asia
root\New Customers\Region\America
root\Deleted Partners
root\New Partners\Region\Europe
root
├── Deleted Customers
│
└── New Customers
│
└── Region
|── Europe
├── Asia
└── America
處理這個問題的最佳pythonic方法是什么?我已經嘗試過binarytree,我可以構建樹,但無法創建完整路徑。
uj5u.com熱心網友回復:
一種更通用的遞回方法和itertools.groupby:
from itertools import groupby as gb
data = {'depth': [0, 1, 1, 2, 3, 3, 3, 1, 1, 2, 3], 'nodeName': ['root', 'Deleted Customers', 'New Customers', 'Region', 'Europe', 'Asia', 'America', 'Deleted Partners', 'New Partners', 'Region', 'Europe']}
def to_tree(n, vals):
r = []
for a, b in gb(vals, key=lambda x:x[0] == n):
if a:
r.extend([j for _, j in b])
else:
r = [*r[:-1], *[r[-1] '\\' j for j in to_tree(n 1, b)]]
yield from r
paths = list(to_tree(0, list(zip(data['depth'], data['nodeName']))))
輸出:
['root\\Deleted Customers',
'root\\New Customers\\Region\\Europe',
'root\\New Customers\\Region\\Asia',
'root\\New Customers\\Region\\America',
'root\\Deleted Partners',
'root\\New Partners\\Region\\Europe']
uj5u.com熱心網友回復:
如果你有一個,binarytree你可以簡單地找到從根到那個節點的路徑。
def hasPath(root, arr, x):
if (not root):
return False
arr.append(root.data)
if (root.data == x):
return True
if (hasPath(root.left, arr, x) or
hasPath(root.right, arr, x)):
return True
arr.pop(-1)
return False
def printPath(root, x):
# vector to store the path
arr = []
if (hasPath(root, arr, x)):
for i in range(len(arr) - 1):
print(arr[i], end = "/")
print(arr[len(arr) - 1])
else:
print("No Path")
uj5u.com熱心網友回復:
有差異的版本
current_path=['']*4
paths=[]
# extend the depth list for the diff
ext_depth=data['depth'] [data['depth'][-1]]
# diff will tell what paths you want to print
diff=list(map(lambda x: x[1]-x[0], zip(ext_depth[1:],ext_depth[:-1])))
for i, val in enumerate(data['depth']):
# update path
current_path[val]=data['nodeName'][i]
if diff[i]>=0:
# join only to the proper depth
paths.append('\\'.join(current_path[:val 1]))
print(paths)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322325.html
下一篇:如果沒有列名,如何提取值?
