gpt4 book ai didi

python - 我将如何基于 Python 中的匹配路径字符串创建列表?

转载 作者:行者123 更新时间:2023-11-28 19:47:31 24 4
gpt4 key购买 nike

我基本上是在尝试将文件路径字符串分隔到同一路径中的文件列表中。假设我有这个列表:

files = ['user/hey.jpg','user/folder1/1.txt','user/folder1/folder2/random.txt',
'user/folder1/blah.txt','user/folder3/folder4/folder5/1.txt',
'user/folder3/folder4/folder5/3.txt','user/folder3/folder4/folder5/2.txt',
'user/1.jpg']

我希望得到这个输出(不关心顺序):

[
['user/folder1/1.txt','user/folder1/blah.txt']
['user/folder1/folder2/random.txt']
['user/folder3/folder4/folder5/1.txt',
'user/folder3/folder4/folder5/2.txt','user/folder3/folder4/folder5/3.txt']
['user/1.jpg','user/hey.jpg']
]

抱歉,如果我的示例草率。在手机上打字并不好玩。感谢您的帮助!

最佳答案

使用 os.path.dirname 作为 sortedgroupby 函数的键应该会引导您得到结果:

import os
from itertools import groupby
[list(g) for _, g in groupby(sorted(files, key=os.path.dirname), key=os.path.dirname)]

#[['user/hey.jpg', 'user/1.jpg'],
# ['user/folder1/1.txt', 'user/folder1/blah.txt'],
# ['user/folder1/folder2/random.txt'],
# ['user/folder3/folder4/folder5/1.txt',
# 'user/folder3/folder4/folder5/3.txt',
# 'user/folder3/folder4/folder5/2.txt']]

关于python - 我将如何基于 Python 中的匹配路径字符串创建列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016456/

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