使用 defaultdict 的 Python 单行树。如何减少所需参数的数量?

标签 python list dictionary defaultdict autovivification

我正在使用这个gist's defaultdict 单行树。

def tree(): return defaultdict(tree)

目前,您必须为要添加的每个节点提供单独的 []

即:

users = tree()
users['harold']['username']['hrldcpr']
users['handler']['username']['matthandlersux']
<小时/>

我的问题是,我如何能够展平输入,以便我可以提供一个列表来实现相同的结果?

即:

users = tree()
users['harold', 'username', 'hrldcpr']
users['handler', 'username', 'matthandlersux']

感谢您的帮助!

最佳答案

您可以简单地定义一个函数,例如insert,通过提供listtree作为参数来创建节点。

def insert(tree, List):
    for node in List:
        tree = tree[node]

users = tree()
insert(users, ['harold', 'username', 'hrldcpr'])

将创建一个结构为 {'harold' : {'username' : {'hrldcp' : {} } } }

关于使用 defaultdict 的 Python 单行树。如何减少所需参数的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26098355/

相关文章:

python - 来自一个 Behave 步骤的数据如何传递到后面的步骤?

多次执行 Python 脚本运行速度变慢

list - 在 Perl 中对列表进行自定义重新排序/排序,时间复杂度为 O(n)

C# XML LINQ 查询到 LIST<>

C++ Map双线程并发插入读取

Python 字典排序

python - 多处理模块映射方法中的赋值(Python)

python - 通知 python orion/quantumleap 订阅更改

python - __import__() 调用 __init__.py 两次?

python - 为什么在修改列表实例时存储对 pop 的函数调用不返回最后一项?