[英]Create a list of lists from dictionary
我有一本字典如下:
d = {'a':['b','c'],'d':['c'],'e':['f'],'i':['g'],'g':['e'],'b':[],'c':[],'h':[],'f':[],}
其中鍵代表每個節點,每個鍵的值代表它們的子節點。
我需要一個 output 如下:
[['a', 'd', 'i', 'h'], ['b', 'c', 'g'], ['e'], ['f']]
列表的列表,其中 list1 具有度數 0(級別 0 節點),列表 2 具有級別 1 節點,列表 3 具有級別 2 節點,依此類推。(內部列表中元素的順序無關緊要) .
輸入字典不會有任何變化。 但是父節點也可以稍后聲明為另一個節點的子節點,這一點必須考慮在內。(例如,這里首先將 e 聲明為 f 的父節點,但稍后將其聲明為 g 的子節點)。
不會有任何重復的父母或鑰匙條目。 樹中的每個節點僅被聲明為一個鍵。 但是不同的鍵會有相同的值,這取決於它們鏈接到哪個父級。
字典中沒有循環的情況。
你們中的任何人都可以幫助我使用相同的 Python 代碼嗎?
(我嘗試了類似於 BFS 算法的東西,但它沒有給我想要的輸出)
你可以用兩個函數來做到這一點。
此算法未優化,但您可以改進它:)
def append_value_at(l, value, index):
# placing value in the index-th list of l. (lists are added if necessary)
if len(l) <= index:
l.append([ value ])
else:
if value not in l[index]:
l[index].append(value)
if len(l) == index:
l.append([ ])
def convert_to_lists(d):
returning = [ ]
for key, values in d.items(): # iterate through the dictionary
# finding index of the key
node = 0
for i in range(len(returning)):
l = returning[i]
for k in l:
if k == key:
node = i
append_value_at(returning, key, node)
for val in values:
append_value_at(returning, val, node + 1)
return returning
d = {'a':['d'],'b':['d','e'],'c':['e','f'],'d':[],'e':['f'],'f':[]}
convert_to_lists(d)
>>> [['a', 'b', 'c'], ['d', 'e', 'f'], ['f']]
**注意:**您的字典有問題,f 是 lvl 1 和 2 節點...但它仍然可以工作:)
希望它有幫助!
凱羅斯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.