【问题标题】:in python, how do i iterate a nested dict with a dynamic number of nests?在 python 中,如何使用动态数量的嵌套迭代嵌套字典?
【发布时间】:2011-10-14 08:19:36
【问题描述】:

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

这是一个字典:

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

【问题讨论】:

    标签: python nested


    【解决方案1】:

    你需要itertools.product

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

    【讨论】:

    • 完美!你应该看看我必须在 php 中经历什么才能实现这一点。
    • 小心你的元素会随机排列
    【解决方案2】:

    与 DrTyrsa 的想法相同,但要确保顺序正确。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      相关资源
      最近更新 更多