Kirovj's Chaos
Write whatever I want. Github


一一 迪迦

Python defaultdict的特殊应用


最近发现 defaultdict 的一个奇技淫巧

defaultdict(default_factory[, ...]) --> dict with default factoryThe default factory is called without arguments to producea new value when a key is not present, in getitem only.A defaultdict compares equal to a dict with the same items.All remaining arguments are treated the same as if they werepassed to the dict constructor, including keyword arguments.


from collections import defaultdict

ind = defaultdict(lambda: len(ind))
var = ind["test_a"]
var1 = ind["test_b"]
var2 = ind["test_a"]
print(var, var1, var2)

0 1 0

本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。