没有Itertools的笛卡尔积没有非Pythonic方法

时间:2013-11-27 18:47:39

标签: python cartesian-product

我这里有这个代码:

import itertools

col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)]

如果没有itertools,我该怎么做?一种非pythonic的方式。

3 个答案:

答案 0 :(得分:2)

如果您只需要两个列表的笛卡尔积,那么可能使用嵌套列表理解。

[ i + j for i in d1_columns for j in d2_columns ]

答案 1 :(得分:1)

def colGroups(d1, d2):
  answer = []
  for c1 in d1:
    for c2 in d2:
      answer.append(c1+c2)
  return answer

测试:

>>> d1 = list(range(10))
>>> d2 = list(range(10,20))
>>> d1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d2
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> def colGroups(d1, d2):
...   answer = []
...   for c1 in d1:
...     for c2 in d2:
...       answer.append(c1+c2)
...   return answer
... 
>>> colGroups(d1, d2)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]

...或嵌套的listcomp等价物:

colGroups = [c1+c2 for c1 in d1 for c2 in d2]

答案 2 :(得分:1)

您始终可以使用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)