如何找到路径列表的公共路径?

时间:2016-03-29 15:16:41

标签: python-2.7

我有一个包含使用' /'作为分隔符,例如:

aaa/bbb/ccc/ddd
aaa/bbb/ccceee
aaa/bbb/ccc/fff

如何在python中编写一个可以返回的函数 字符串' aaa / bbb /'?

3 个答案:

答案 0 :(得分:1)

我是python的新手(昨天开始),但这就是我提出的:

paths = [ 'aaa/bbb/ccc/ddd/eee', 'aaa/bbb/ccceee/fff', 'aaa/bbb/ddd/eee', 'aaa/bbb/' ]

def get_common_path(paths):
    common = []
    common_size = -1

    for p in paths:
        s = p.split('/')
        s.pop()
        if common_size == -1:
            common_size = len(s)
            common = s
            continue
        while common_size > 0 and s[0:common_size] != common:
            common_size -= 1
            common.pop()

    return '/'.join(common) + '/'

common_path = get_common_path(paths)
print 'Common path = \'{}\'; length = {}'.format(common_path, len(common_path))

输出:

Common path = 'aaa/bbb/'; length = 8

答案 1 :(得分:0)

像你发布的新行分隔输入:

paths = """
aaa/bbb/ccc/ddd
aaa/bbb/ccceee
aaa/bbb/ccc/fff
""" 

列表理解的隐秘,hacky混合,zip()set()join()

common = "".join([y[0] for y in zip(*[x for x in paths.split("\n") if any(x)]) if len(set(y)) == 1])
print common[:common.rfind("/")+1]

答案 2 :(得分:0)

Commonpath 为您做到这一点:

DependsOn