如何获得所有子元素的所有完整路径

时间:2019-06-28 09:47:25

标签: python-3.x recursion data-structures tree

给出一个基于列表列表的树:

tree = [
  "A",
  [
    "B1",
    [
      "C"
    ]
  ],
  [
    "B2",
    [
      "C",
      [
        "D1",
        [
          "E1"
        ],
        [
          "E2"
        ]
      ],
      [
        "D2"
      ]
    ]
  ]
]

我想获取所有子元素的完整路径作为列表中的连接字符串。

result = [
  'A>B1>C',
  'A>B2>C>D1>E1',
  'A>B2>C>D1>E2',
  'A>B2>C>D2'
]

定界符>可以更改。

我尝试了递归和收益不同的事情。但是我的头在燃烧。

2 个答案:

答案 0 :(得分:2)

尝试一下即可。

def leave_paths(current):
    if len(current) == 1:
        return [current]
    # Take all branches, get the paths for the branch, and prepend
    return [[current[0]] + path for branch in current[1:] for path in leave_paths(branch)]

output = ['>'.join(sub_list) for sub_list in leave_paths(s)]
print(output)

输出

['A>B1>C', 'A>B2>C>D1>E1', 'A>B2>C>D1>E2', 'A>B2>C>D2']

答案 1 :(得分:0)

像这样的东西

def findLeaves(tree):
   name=tree[0]
   If len(tree)==1:
      return [name]
   else:
      return [name+"->"+path for branch in tree[1:] for path in findLeaves(branch)]