Python减少嵌套字典中的嵌套循环
我的字典结构如下所示:Python减少嵌套字典中的嵌套循环,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我的字典结构如下所示: mapping = {'outputs': {'cube1': {'tx': 1.0}}} 我这样重复它们: for node, props in mapping['outputs'].items(): for prop, value in props.items(): #Further loops 有没有一种优雅的方法可以将这两个嵌套循环折叠为一个 因此,我希望得到以下结果: for node, prop, value in nest_loo
mapping = {'outputs': {'cube1': {'tx': 1.0}}}
我这样重复它们:
for node, props in mapping['outputs'].items():
for prop, value in props.items():
#Further loops
有没有一种优雅的方法可以将这两个嵌套循环折叠为一个
因此,我希望得到以下结果:
for node, prop, value in nest_loop(mapping['outputs']):
#Further loops
可以使用生成器表达式执行与嵌套for循环类似的工作。范例-
nest_loop = ((a,b,c) for a,x in mapping['outputs'].items() for b,c in x.items())
for node, prop, value in nest_loop:
#Do work
但我更喜欢可读性更强的嵌套循环
演示-
>>> mapping = {'outputs': {'cube1': {'tx': 1.0}}}
>>> nest_loop = ((a,b,c) for a,x in mapping['outputs'].items() for b,c in x.items())
>>> for node, prop, value in nest_loop:
... print(node,prop,value)
...
cube1 tx 1.0
不确定这是否是您想要的:
对于节点,属性,值位于[(节点,属性,值)对于节点,属性位于映射[“输出”]。对于属性,值位于属性。项目()
打印节点、道具、值
必须将不美观封装到生成器函数中。我现在正赶不上进度,或者我会从我刚才说的话中做出一个答案谢谢你的回答,我想把这两个问题折叠起来的原因是我有更多的循环。目前我的代码中有与解决方案完全相同的生成器表达式,但我仍然愿意接受更多的想法。