in python, how do i iterate a nested dict with a dynamic number of nests?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 15:10:27

问题


OK by dynamic I mean unknown at runtime.

here is a dict:

aDict[1]=[1,2,3]
aDict[2]=[7,8,9,10]
aDict[n]=[x,y]

I don't know how many n will be but I want to loop as follows:

for l1 in aDict[1]:
  for l2 in aDict[2]:
    for ln in aDict[n]:
      # do stuff with l1, l2, ln combination.

Any suggestions on how to do this? I am relatively new to python so please be gentle (although I do program in php). BTW I am using python 3.1


回答1:


You need itertools.product.

from itertools import product

for vals in product(*list(aDict.values())):
    # vals will be (l1, l2, ..., ln) tuple



回答2:


Same idea as DrTyrsa, but making sure order is right.

from itertools import product

for vals in product( *[aDict[i] for i in sorted(aDict.keys())]):
    print vals


来源:https://stackoverflow.com/questions/7764892/in-python-how-do-i-iterate-a-nested-dict-with-a-dynamic-number-of-nests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!