动态确定我的意思是在运行时未知。
这是一个字典:
aDict[1]=[1,2,3]
aDict[2]=[7,8,9,10]
aDict[n]=[x,y]
我不知道 n 是多少,但我想按如下方式循环:
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
最佳答案
你需要itertools.product .
from itertools import product
for vals in product(*list(aDict.values())):
# vals will be (l1, l2, ..., ln) tuple
关于python - 在 python 中,我如何迭代具有动态嵌套数的嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764892/