首页 > 解决方案 > 如何获取所有子元素的所有完整路径

问题描述

给定基于列表列表的树:

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'
]

分隔符>是可变的。

我用递归和产量尝试了不同的东西。但我的头在燃烧。

标签: python-3.xrecursiondata-structurestree

解决方案


试试这个它有效。

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']


推荐阅读