gpt4 book ai didi

python - 如何按 parent 对路径列表进行分组?

转载 作者:行者123 更新时间:2023-12-02 15:44:47 24 4
gpt4 key购买 nike

我有一个路径列表,我希望它们根据它们来自的文件夹名称动态地分成它们应该属于的列表。前两个来自 “tent1” 文件夹,我希望它们在一个列表中,依此类推。我不想硬编码这些文件夹的名称,然后将路径附加到它们。例如:

paths = [
'/var/lib/cons/states/tent1/tops-ok_2022_11_28',
'/var/lib/cons/states/tent1/tops-ok_2022_11_27',
'/var/lib/cons/states/tent2/tops-ok_2022_11_28',
'/var/lib/cons/states/tent2/tops-ok_2022_11_27',
'/var/lib/cons/states/tent3/tops-ok_2022_11_28',
'/var/lib/cons/states/tent3/tops-ok_2022_11_27',
'/var/lib/cons/states/tent4/tops-ok_2022_11_28',
'/var/lib/cons/states/tent4/tops-ok_2022_11_27',
]

我希望他们是这样的:

[['/var/lib/cons/states/tent1/tops-ok_2022_11_28', 
'/var/lib/cons/states/tent1/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent2/tops-ok_2022_11_28',
'/var/lib/cons/states/tent2/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent3/tops-ok_2022_11_28',
'/var/lib/cons/states/tent3/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent4/tops-ok_2022_11_28',
'/var/lib/cons/states/tent4/tops-ok_2022_11_27']]

最佳答案

如果您的输入按路径排序(即相同的路径是连续的),您可以使用 itertools.groupby :

from itertools import groupby
from os.path import dirname

out = [list(g) for _,g in groupby(paths, dirname)]

如果路径没有排序,你可以使用字典作为中间:

out = {}
for p in paths:
(out.setdefault(dirname(p), [])
.append(p)
)

out = list(out.values())

输出:

[['/var/lib/cons/states/tent1/tops-ok_2022_11_28',
'/var/lib/cons/states/tent1/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent2/tops-ok_2022_11_28',
'/var/lib/cons/states/tent2/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent3/tops-ok_2022_11_28',
'/var/lib/cons/states/tent3/tops-ok_2022_11_27'],
['/var/lib/cons/states/tent4/tops-ok_2022_11_28',
'/var/lib/cons/states/tent4/tops-ok_2022_11_27']]

替代pathlib :

from itertools import groupby
from pathlib import Path

out = [list(g) for _,g in groupby(paths, lambda x: Path(x).parent)]

关于python - 如何按 parent 对路径列表进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74612068/

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