Nested defaultdict of defaultdict

前端 未结 8 2322
谎友^
谎友^ 2020-11-22 12:19

Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)

I want to be able to do:

x         


        
8条回答
  •  盖世英雄少女心
    2020-11-22 12:37

    Similar to BrenBarn's solution, but doesn't contain the name of the variable tree twice, so it works even after changes to the variable dictionary:

    tree = (lambda f: f(f))(lambda a: (lambda: defaultdict(a(a))))
    

    Then you can create each new x with x = tree().


    For the def version, we can use function closure scope to protect the data structure from the flaw where existing instances stop working if the tree name is rebound. It looks like this:

    from collections import defaultdict
    
    def tree():
        def the_tree():
            return defaultdict(the_tree)
        return the_tree()
    

提交回复
热议问题