【问题标题】:nested dictionary comprehension - dictionary of dictionaries嵌套字典理解 - 字典字典
【发布时间】:2021-07-24 17:38:52
【问题描述】:

我应该如何通过字典推导获得所需的输出?

{'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

【问题讨论】:

标签: python dictionary dictionary-comprehension


【解决方案1】:

开始慢慢工作。我喜欢从最里面的项目开始,然后向外工作。

你开始于:

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')
}

【讨论】:

  • 非常感谢您的即时回复。
  • @kalaivananramalingam 如果它解决了您的问题,请考虑支持或标记正确! :)
  • 看来我需要 15 个声望。我无法投票。我将其标记为正确。
  • 很好,但是('B', 'C', 'D') 需要一个右括号。我意识到这几乎是微不足道的,但我个人的喜好是使用 for i in 'BCD' - 可读性更高且更简洁(只要它始终是键的单个字符)。
  • @JamieDeith 感谢您的支架。尽管字符串可以用作可迭代对象,但当键需要多个字符时,这种模式很快就会失效。从个人偏好的角度来看,显式列表代码更多,但也更具可读性。
猜你喜欢
  • 2017-11-27
  • 2013-11-30
  • 2013-07-28
  • 2011-06-06
  • 2016-11-25
  • 2020-12-15
  • 2021-12-20
  • 2016-12-25
相关资源
最近更新 更多