【问题标题】:Flattening a very nested loop [duplicate]展平一个非常嵌套的循环[重复]
【发布时间】:2013-08-21 23:27:32
【问题描述】:

如果我有一组这样的循环:

x = [[...],[...],[...]]    

for a in x[0]:
  for b in x[1]:
    for c in x[2]:
      # Do something with a,b,c

有没有一种简单的方法来简化它,尤其是在它有更多级别的情况下?这似乎很容易做到,但我就是想不通。

【问题讨论】:

    标签: python loops for-loop


    【解决方案1】:

    使用 itertools 库非常简单。

    for x, y, z in itertools.product(a, b, c):
        print x, y, z
    

    如何实现itertools.product

    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)
    

    例子:

    In [1]: a = range(2)    
    In [2]: b = range(2, 4)
    In [3]: c = range(4, 6)
    In [4]: import itertools
    In [5]: list(itertools.product(a, b, c))
    Out[5]: 
    [(0, 2, 4),
     (0, 2, 5),
     (0, 3, 4),
     (0, 3, 5),
     (1, 2, 4),
     (1, 2, 5),
     (1, 3, 4),
     (1, 3, 5)]
    
    In [6]: for x, y, z in itertools.product(a, b, c):
       ...:     print 'x: %d, y: %d, z: %d' % (x, y, z)
       ...: 
    x: 0, y: 2, z: 4
    x: 0, y: 2, z: 5
    x: 0, y: 3, z: 4
    x: 0, y: 3, z: 5
    x: 1, y: 2, z: 4
    x: 1, y: 2, z: 5
    x: 1, y: 3, z: 4
    x: 1, y: 3, z: 5
    

    【讨论】:

    • 我想你的意思是itertools.product(*x)
    • 会不会更像itertools.product(*x)?,还是itertools.product(x[0], x[1], x[2])
    • 谢谢,对上述 cmets 之一的更改有效。我还注意到,如果您使用for a in,它将在一个元组中交付所有内容!
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 2021-02-06
    • 2019-12-19
    • 2017-07-20
    • 2014-06-11
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    相关资源
    最近更新 更多