我有一個包含模塊名稱的字典,作為一個值,它包含其子模塊的串列,每個子模塊都定義為 ['Absolute Name', 'Relative Name'],絕對名稱是它可以使用的名稱如果已將此類模塊插入字典,則在我的字典中找到作為鍵。
modules_dict = {
"ModuleB": [],
"ModuleA": [
[
"ModuleB",
"Realtive_B"
],
[
"ModuleC",
"Relative_C"
],
],
"ModuleC": [
[
"ModuleE",
"Realtive_E"
],
[
"ModuleD",
"Relative_D"
]] }
我的目標是為每個模塊/子模塊制作“層次結構”字串,其中每個字串都是模塊的相對層次結構。對于這個例子,這將是:
ModuleA.Realtive_B
ModuleA.Relative_C.Realtive_E
ModuleA.Relative_C.Relative_D
ModuleA.Relative_C
到目前為止,我撰寫的代碼在某些情況下實作了這一點,但如果層次結構變得過于復雜,則某些字串中會出現重復的片段,例如:
ModuleA.RelativeB.RelativeC.RelativeA.RelativeB.RelativeG
在我的函式開始時,我將它傳遞給它將使用的層次結構的根
hierarchy_strings = []
def name_change(submodules,upper_name):
submodules[1] =upper_name "." submodules[1] # submodules is a list containing absolute and relative name of a submodule ( the values of my dict )
return submodules
def scan_submodule(module):
try:
for submodules in modules_dict[module[0]]:
local_module_info = name_change(submodules,module[1])
scan_submodule(local_module_info)
hierarchy_strings.append(local_module_info[1])
print(local_module_info[1])
except KeyError:
pass
top_module= ["ModuleA","ModuleA"]
scan_submodule(top_module)
我的思維方式一定有錯誤,但我就是想不通。
uj5u.com熱心網友回復:
您可以使用遞回生成器,如下所示:
def iterPaths(modules, root, path=""):
if not path: # Set default for path
path = root
yield path
if root not in modules or not modules[root]:
return
for child, label in modules[root]:
yield from iterPaths(modules, child, path "." label)
for path in iterPaths(modules, "ModuleA"):
print(path)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488116.html
