3

我有一个文件名列表,并希望将它们打印为目录树:

files = ["foo/bar/Bla", "foo/bar/Foo", "foo/foo/Bsdf", "xsd/sdafd/saasf"]
[...]
# output should look like this 
output = ['foo' : ['bar' : ['Bla', 'Foo'], 'foo' : ['Bsdf']], 'xsd' : ['sdafd' : ['saasf']]]

我尝试了不同的方法,但我不能比这样的事情更进一步:

['foo/bar': ['Bla', 'Foo'], 'foo/foo/': ['Bsdf'], 'xsd/sdafd' : ['saasf']]

或类似的...

4

2 回答 2

1

此代码适用于您的输入:

def recurse_setdefault(res, array):
    if len(array) == 0:
        return
    elif len(array) == 1:
        res.append(array[0])
    else:
        recurse_setdefault(res.setdefault(array[0], [] if len(array) == 2 else {}), array[1:])

res = {}
for f in files:
    recurse_setdefault(res, f.split("/"))

结果是:

{'foo': {'bar': ['Bla', 'Foo'], 'foo': ['Bsdf']}, 'xsd': {'sdafd': ['saasf']}}
于 2013-07-16T11:24:57.847 回答
1

无法获得单线

files = ["foo/bar/Bla", "foo/bar/Foo", "foo/foo/Bsdf", "xsd/sdafd/saasf"]

dict_add = lambda x, y={}: dict_add(x[:-1], y).setdefault(x[-1], {}) if(x) else y
base_dict = {}
map(lambda x: dict_add(x, base_dict), [path.split("/") for path in files])
于 2013-07-16T11:32:36.977 回答