猿问

Python:获取路径中所有父项的可迭代的优雅方法

使用基于路径的资源系统,应用程序需要根据路径找到管理给定资源的第一个工作资源。我需要一种简洁的 Pythonic 方式来生成以下内容:


输入:


/house/dogs/ralph/bone

输出:


/house/dogs/ralph/bone

/house/dogs/ralph

/house/dogs

/house

注意:可以使用os.path或类似的内置函数,但这些不是文件系统资源。输出可以是任何可迭代的(列表、集合、生成器等)。


海绵宝宝撒
浏览 193回答 3
3回答

qq_笑_17

使用pathlib. PurePaths 为与文件系统没有关系的类路径对象提供抽象接口。特别PurePosixPath是使用正斜杠 ( /) 作为分隔符的类型:>>> from pathlib import PurePosixPath>>> p = PurePosixPath('/house/dogs/ralph/bone')>>> str(p.parent)/house/dogs/ralph>>> str(p.parent.parent)/house/dogs您可以轻松循环:p = PurePosixPath(...)while p != p.root:    # Do stuff to p    p = p.parent一个相当 Pythonic 的画龙点睛是使它成为一个生成器:def receding_path(p):    p = PurePosixPath(p)    while p != p.root:        yield str(p)        p = p.parentfor item in receding_path('/house/dogs/ralph/bone'):    # do stuff to each item

蝴蝶刀刀

一种方法是拆分字符串"/"并连续切片。in_string = "/house/dogs/ralph/bone"s = in_string.split("/")out_strings = list(filter(None, ("/".join(s[:i+1]) for i in range(len(s)))))print(out_strings)#['/house', '/house/dogs', '/house/dogs/ralph', '/house/dogs/ralph/bone']该filter(None, ...)用于去除空字符串。如果您希望按照您在帖子中指定的顺序输出,或者反转范围:out_strings = list(filter(None, ("/".join(s[:i]) for i in range(len(s), 0, -1))))print(out_strings)#['/house/dogs/ralph/bone',# '/house/dogs/ralph',# '/house/dogs',# '/house']

牧羊人nacy

前两个答案的组合:import pathlibimport osdef resources(path):  parts = pathlib.Path(path).parts  for n in range(len(parts), 1, -1):    yield os.path.join(*parts[:n])
随时随地看视频慕课网APP

相关分类

Python
我要回答