gpt4 book ai didi

python - 合并文件路径列表

转载 作者:行者123 更新时间:2023-12-04 08:55:34 25 4
gpt4 key购买 nike

我有一个目录路径列表,我试图将其减少到可能的最小列表。例如:

bionic/main/installer-amd64/20101020ubuntu543/images/hd-media
bionic/main/installer-amd64/20101020ubuntu543/images/cdrom/xen
bionic/main/installer-amd64/20101020ubuntu543/images/cdrom
bionic/main/installer-amd64/20101020ubuntu543/images
bionic/main/installer-amd64/20101020ubuntu543
我可以摆脱 bionic/main/installer-amd64/20101020ubuntu543因为它可以折叠成 bionic/main/installer-amd64/20101020ubuntu543/images我也可以摆脱它,因为它可以折叠成 bionic/main/installer-amd64/20101020ubuntu543/images/cdrom然后折叠成 bionic/main/installer-amd64/20101020ubuntu543/images/cdrom/xen我知道有一种方法可以做到这一点,但我一生都无法弄清楚。

最佳答案

如果我正确理解您的问题,您可以将目录放入树结构中,然后从该树中获取叶节点,这些目录不是列表中另一个目录的父目录。

dirs = ["bionic/main/installer-amd64/20101020ubuntu543/images/hd-media",
"bionic/main/installer-amd64/20101020ubuntu543/images/cdrom/xen",
"bionic/main/installer-amd64/20101020ubuntu543/images/cdrom",
"bionic/main/installer-amd64/20101020ubuntu543/images",
"bionic/main/installer-amd64/20101020ubuntu543"]

tree = {}
for d in dirs:
t = tree
for x in d.split("/"):
t = t.setdefault(x, {})
# {'bionic': {'main': {'installer-amd64': {'20101020ubuntu543': {'images': {'hd-media': {}, 'cdrom': {'xen': {}}}}}}}}

def leafs(tree):
for x in tree:
if tree[x]:
for l in leafs(tree[x]):
yield x + "/" + l
else:
yield x

for l in leafs(tree):
print(l)
# bionic/main/installer-amd64/20101020ubuntu543/images/hd-media
# bionic/main/installer-amd64/20101020ubuntu543/images/cdrom/xen

关于python - 合并文件路径列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63848503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com