Python 将文件系统映射到目录结构 : works, ...但是如何呢?

标签 python reduce

我正在解析一个目录。我找到了 a snippet here ,效果很好,但我似乎无法弄清楚它们的变量 dir 为何以及如何在设置的位置更新。

我想做的是去掉空文件夹

import os

def get_directory_structure(rootdir):
    """
    Creates a nested dictionary that represents the folder structure of rootdir
    """
    dir = {}
    rootdir = rootdir.rstrip(os.sep)
    start = rootdir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(rootdir):
        folders = path[start:].split(os.sep)
        subdir = dict.fromkeys(files)
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir

dir 被设置为与 parent 相同的值:

        parent[folders[-1]] = subdir

怎么会?

dir 是可变的,并作为 reduce 行中的输入,但它不是在那里设置的,而是在下面的行中设置的。

有什么想法吗?

我希望能够省去空文件夹,而宁愿找到一种优雅的方式来做到这一点;我应该放弃并浏览字典作为第二遍吗?

[解决后编辑] 正如 Hans 和 Adrin 指出的那样,reduce 实际上使父对象指向 dir,因此它们是同一个对象,并且对父对象的任何更新都会更新 dir。

我最终保留了相同的代码,但为清楚起见重命名了变量:

dir -> token_dict
文件夹 -> path_as_list
子目录 -> files_in_dir
parent -> full_dir(我最终返回了 full_dir)

更多的输入,但下次我看的时候,我会马上开始。

最佳答案

对于不太熟悉 reduce 的人,关于使用字典进行 reduce 的一些解释:

在我们介绍代码片段之前,让我们先做一些 reduce 函数。

Reduce 会将两个参数的函数累积应用于序列的项目, 从左到右,以便将序列减少为单个值。

语法如下:

reduce(function, sequence[, initial]) -> value

如果存在initial,则在计算中将其放在序列项之前, 并在序列为空时用作默认值。

没有首字母:

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15
>>>
smiliar to ((((1+2)+3)+4)+5)

首字母:

>>> reduce(lambda x, y: x+y, [], 1) 
1
>>>

说到列表,说到字典:

首先让我们检查一下 dict.get() 方法可以做什么:

>>> d = {'a': {'b': {'c': 'files'}}}
>>> dict.get(d,'a')
{'b': {'c': 'files'}}
>>>

因此,当您将 dict.get 方法放入 reduce 时,会发生以下情况:

>>> d = {'a': {'b': {'c': 'files'}}}
{'b': {'c': 'files'}}
>>> reduce(dict.get, ['a','b','c'], d)
'files'
>>>

类似于:

>>> dict.get(dict.get(dict.get(d,'a'),'b'),'c')
'files'
>>>

当你得到空列表时,你会得到空字典,这是默认值:

>>> reduce(dict.get, [], {})
{}
>>>

让我们回到您的代码段:

您代码段中的 dir != builtin dir() 函数,它只是一个绑定(bind)到空字典的名称。

parent = reduce(dict.get, folders[:-1], dir)

因此,在上一行中,folders[:-1] 只是一个目录列表。 dir 是 empty_dictionary。

如果有帮助,请告诉我。

关于Python 将文件系统映射到目录结构 : works, ...但是如何呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455021/

相关文章:

python - pydantic 模型动态字段数据类型

python - 在创建 pytorch NN 模块时使用列表

Clojure 的 Map 和 Reduce Monad... Juxt Monad 怎么样?

hadoop - 如果 Hive 的 reducer 数量与键的数量不同,会发生什么?

c - 具有相同类型字段的结构上的 MPI_Allreduce 是否可移植?

python - Django View 中的异步函数

python - 仅包含 ASCII 字符的 UNICODE 字符串是否总是等于 ASCII 字符串?

python - 如何在 MacOS 上使用 Xcode 从源代码构建和调试 python 可执行文件(python 解释器)

javascript - CouchDB,如何在一个 View 中计算两个值

javascript - 如何在Javascript中使用reduce函数编写嵌套数组