在python中,如何迭代具有动态嵌套数的嵌套字典? [英] in python, how do i iterate a nested dict with a dynamic number of nests?

查看:91
本文介绍了在python中,如何迭代具有动态嵌套数的嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态确定,我的意思是运行时未知.

OK by dynamic I mean unknown at runtime.

这是一个字典:

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

我不知道n是多少,但是我想循环如下:

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.

有关如何执行此操作的任何建议?我是python的新手,所以请保持柔和(尽管我使用php编程).顺便说一句,我正在使用python 3.1

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

推荐答案

您需要 itertools.product .

from itertools import product

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

这篇关于在python中,如何迭代具有动态嵌套数的嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆