python – 展平非常嵌套的循环
发布时间:2020-12-20 11:29:12 所属栏目:Python 来源:网络整理
导读:参见英文答案 Avoiding nested for loops????????????????????????????????????2个 如果我有一组像这样的循环: x = [[...],[...],[...]] for a in x[0]: for b in x[1]: for c in x[2]: # Do something with a,b,c 有没有一种简单的方法来简化它,特别是如果
参见英文答案 >
Avoiding nested for loops????????????????????????????????????2个
如果我有一组像这样的循环: x = [[...],[...],[...]] for a in x[0]: for b in x[1]: for c in x[2]: # Do something with a,b,c 有没有一种简单的方法来简化它,特别是如果它有更多的级别?这似乎很容易做到,但我无法弄清楚. 解决方法
使用itertools库非常容易.
for x,y,z in itertools.product(a,c): print x,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,c)) Out[5]: [(0,2,4),(0,5),3,(1,5)] In [6]: for x,c): ...: print 'x: %d,y: %d,z: %d' % (x,z) ...: x: 0,y: 2,z: 4 x: 0,z: 5 x: 0,y: 3,z: 5 x: 1,z: 4 x: 1,z: 5 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |