我一直在尝试构建具有n层且列表为“叶子”的嵌套defaultdict。我想复制以下行为:
#include <string>
#include <iostream>
#include <stdint.h>
int main()
{
std::string a("\xaa\x00\x00\xaa", 4);
int u = *(int *) a.c_str();
unsigned int v = *(unsigned int *) a.c_str();
int32_t x = *(int32_t *) a.c_str();
uint32_t y = *(uint32_t *) a.c_str();
std::cout << a << std::endl;
std::cout << "int: " << u << std::endl;
std::cout << "uint: " << v << std::endl;
std::cout << "int32_t: " << x << std::endl;
std::cout << "uint32_t: " << y << std::endl;
return 0;
}
所以我尝试了以下方法:
>>> from collections import defaultdict
>>> template_d = defaultdict(lambda : defaultdict(lambda : defaultdict(list)))
>>> template_d['a']['b']['c']
[]
>>> template_d['a']['b']['c'].append('first_element')
>>> template_d['a']['b']['c']
['first_element']
我想拥有:
from collections import defaultdict
def template_dict(n_layers):
d = defaultdict(list)
for i in range(n_layers - 1):
d = defaultdict(lambda : d)
return d
但是我有:
>>> template_d = template_dict(3)
>>> template_d['a']['b']['c']
[]
关于为什么它无法按预期运行以及如何解决的任何想法? :)