【问题标题】:How to get all full paths to all child elements如何获取所有子元素的所有完整路径
【发布时间】:2019-11-10 06:40:00
【问题描述】:

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

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.x recursion data-structures tree


【解决方案1】:

试试这个吧。

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

【讨论】:

    【解决方案2】:

    这样的事

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

    【讨论】:

      猜你喜欢
      • 2017-01-05
      • 2014-09-07
      • 2019-07-18
      • 1970-01-01
      • 2021-12-08
      • 2021-06-11
      • 2016-11-06
      • 1970-01-01
      • 2019-07-10
      相关资源
      最近更新 更多