编程语言
首页 > 编程语言> > python – 访问没有嵌套循环的字典的嵌套级别

python – 访问没有嵌套循环的字典的嵌套级别

作者:互联网

我有一个字典,其中包含各种n值的协议的仿真结果(“协议”和n与我面临的问题无关).这本词典的结构如下:

myDict = {"protocol1" : {1:[some list of numbers], 2:[another list of numbers]},
          "protocol2" : {1:[some list of numbers], 2:[another list of numbers]},
         }

现在,为了分析结果,我会做这样的事情:

for protocol, stats in myDict.items():
  for n, counts in stats.items():
    # do stuff with protocol, n and counts

我想知道,如果存在一些允许我这样做的内置函数,而不必定义自定义迭代器:

for protocol, n, counts in magicFunc(myDict):
  # do stuff with protocol, n and counts

在itertools中是否有某些东西可以让我这样做?

解决方法:

不确定它是否更好……我会坚持你的榜样,但它会变得更深,比如:

myDict = {
    'p1': {1: [1, 2, 3], 2: [4, 5, 6]},
    'p2': {3: [7, 8, 9], 4: [0, 1, 2]}
}

from collections import Mapping

def go_go_gadget_go(mapping):
    for k, v in mapping.items():
        if isinstance(v, Mapping):
            for ok in go_go_gadget_go(v):
                yield [k] + ok
        else:
            yield [k] + [v]

for protocol, n, counts in go_go_gadget_go(myDict):
    print(protocol, n, counts)

# p2 3 [7, 8, 9]
# p2 4 [0, 1, 2]
# p1 1 [1, 2, 3]
# p1 2 [4, 5, 6]

标签:python,dictionary,python-3-x,python-3-3
来源: https://codeday.me/bug/20190624/1281170.html