- 在 python 2.5中,函数类似于 itertools.product的方式

  显示原文与译文双语对照的内容
147 4

我有元组的列表,e.g:

A=[(1,2,3), (3,5,7,9), (7)] 

并希望从每个元组中生成一个项的所有排列。

1,3,7
1,5,7
1,7,7
...
3,9,7

任何数量的元组和一个元组都可以有任意数量的元素。我不能使用 itertools.product(),因为 python 2.5.

时间:原作者:0个回答

112 0

itertools.product 文档有一个示例,说明如何在 py2.5 中实现它:

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)
原作者:
125 2
def product(*iterables):
""" Equivalent of itertools.product for versions <2.6,
 which does NOT build intermediate results.
 Omitted 'repeat' option.
 product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
"""
 nIters = len(iterables)
 lstLenths = []
 lstRemaining = [1]
 for i in xrange(nIters-1,-1,-1):
 m = len(iterables[i])
 lstLenths.insert(0, m)
 lstRemaining.insert(0, m * lstRemaining[0])
 nProducts = lstRemaining.pop(0)
 for p in xrange(nProducts):
 lstVals = []
 for i in xrange(nIters):
 j = p/lstRemaining[i]%lstLenths[i]
 lstVals.append(iterables[i][j])
 yield tuple(lstVals)
原作者:
...