python-3.x - 如何获取所有子元素的所有完整路径
问题描述
给定基于列表列表的树:
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'
]
分隔符>
是可变的。
我用递归和产量尝试了不同的东西。但我的头在燃烧。
解决方案
试试这个它有效。
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']
推荐阅读
- mysql - 使用“喜欢”时如何在不重复的情况下合并结果
- apex - 在 visualforce 页面中编辑自定义对象记录
- spring-mvc - Spring RestTemplate 不允许持久的 https 连接
- node.js - 如何在 Circuit JavaScript SDK 中获取向机器人发送消息的用户的电子邮件?
- python - Python使用当前模块中定义的变量从不同模块调用函数
- kubernetes - 无法在 ingress-nginx-controller 上配置 UDP
- java - 如果 json 数组为空,则 Gson getAsString() 失败
- r - 应用 rbinom 时在 data.table .SD 中应用的列特定参数
- android - 检查两个点的 ArrayList 是否对称
- angular - 订阅 angular observable 是未定义的