[英]nested dictionary comprehension - dictionary of dictionaries
我该如何通过字典理解来实现所需的 output ?
{'R': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}},
'L': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}},
'B': {0: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
3: {2: 0, 3: 0, 4: 0, 5: 0, 1: 0}}}
我通过下面的代码得到了它:
d_clas = {'B':{} , 'C':{}, 'D':{}}
l_uniq = [array([1, 2, 3, 4, 5], dtype=int64),
array([1, 2, 3, 4, 5], dtype=int64),
array([1, 2, 3, 4, 5], dtype=int64),
array([2, 3, 4, 5, 1], dtype=int64)]
for i in d_clas:
c_clas = {}
for j in range(len(l_uniq)-1):
c_clas[j] = {}
for k in l_uniq[j]:
c_clas[j][k] = 0
d_clas[i] = c_clas
慢慢开始你的工作。 我喜欢从最里面的项目开始,然后向外工作。
你开始:
d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
c_clas = {}
for j in range(len(l_uniq)-1):
c_clas[j] = {}
for k in l_uniq[j]:
c_clas[j][k] = 0
d_clas[i] = c_clas
首先做最里面的结构:
d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
c_clas = {}
for j in range(len(l_uniq)-1):
c_clas[j] = {k: 0 for k in l_uniq[j]}
d_clas[i] = c_clas
然后下一个:
d_clas = {'B':{} , 'C':{}, 'D':{}}
for i in d_clas:
d_clas[i] = {
j: {k: 0 for k in l_uniq[j]}
for j in range(len(l_uniq) - 1)
}
最后是最后一个结构:
d_clas = {
i: {
j: {k: 0 for k in l_uniq[j]}
for j in range(len(l_uniq) - 1)
}
for i in ('B', 'C', 'D')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.