python - 在 python 中,我如何迭代具有动态嵌套数的嵌套字典?

标签 python nested

动态确定我的意思是在运行时未知。

这是一个字典:

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/

相关文章:

python - 为什么我的表格总是未绑定(bind)?

具有多重嵌套 JOIN 和不同有限排序的 MySQL 语句

java - 如何让 while 循环中的 if else 嵌套循环正常工作,

javascript - Django 中的空 queryDict

python - 突变后更新动态依赖的对象属性

python - 在 Oracle DB 上从 python 运行 set role 命令

python - 使用 matplotlib 在 x 轴上设置最小/最大年份

c++ - 嵌套模板中的运算符= (T *r)

c++ - C++类中的C'tor

mysql - 在 PHP 中,如何使用跨不同表的多个 "IN"语句查询 mySQL 数据库?