使用 Python 内置的 defaultdict
,我们可以很容易的定义一个树形数据结构:
def tree(): return defaultdict(tree)
就是这样!
使用 Python 内置的 defaultdict
,我们可以很容易的定义一个树形数据结构:
def tree(): return defaultdict(tree)
就是这样!
The other day, I saw Harold Cooper's One-line tree in Python via autovivication, and wondered if the same thing was possible in Groovy.
The answer is yes! But you need to define the variable tree
before you can assign it to the self-referential withDefault
closure, hence with Groovy, it's a two-line solution ;-)
Anyway, given:
def tree = { [:].withDefault{ owner.call() } }