展平一个非常嵌套的循环 [英] Flattening a very nested loop

查看:88
本文介绍了展平一个非常嵌套的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样一组循环:

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

for a x [0]:
for b in x [1]:
for c in x [2]:
#做一些与a,b,c

有一个简单的方法来简化它,尤其是如果有更多的级别呢?这似乎是一件很容易做的事情,但我无法弄清楚。

解决方案

itertools
$ b $ pre $ for itertools.product(a,b,c)中的x,y,z:
print x ,y,z

itertools.product 可以执行:

$ $ $ $ $ $ $ $ $ def $ product $ * $ b $ product('ABCD', 'xy') - > A x A x Bx通过Cx Cy Dx Dy
#product(范围(2),repeat = 3) - > 000 001 010 011 100 101 110 111
pool = map(tuple,args)* kwds.get('repeat',1)
result = [[]]
池中的池:
result = [x + [y] for x for result in y in pool]
for prod in result:
yield元组(prod)

示例:

  In [1]:a =范围(2)
在[2]中:b =范围(2,4)
在[3]中:c =范围(4,6)
在[4]中:import itertools
在[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)]

在[6]中:for itertools.product中的x,y,z (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


If I have a set of loops like this:

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

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

Is there a simple way to simplify it, especially if there are more levels to it? It seems like something quite easy to do, but I just can't figure it out.

解决方案

It's quite easy with the itertools library.

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

How itertools.product could be implemented:

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)

Example:

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

这篇关于展平一个非常嵌套的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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