不含Itertools的笛卡尔积非Pythonic方法

不含Itertools的笛卡尔积非Pythonic方法,python,cartesian-product,Python,Cartesian Product,我这里有这个代码: import itertools col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)] 没有itertools我怎么能做这样的事情?一种非蟒蛇式的方式 def colGroups(d1, d2): answer = [] for c1 in d1: for c2 in d2: answer.append(c1+c2) return answe

我这里有这个代码:

import itertools

col_groups = [c1+c2 for c1, c2 in itertools.product(d1_columns, d2_columns)]
没有itertools我怎么能做这样的事情?一种非蟒蛇式的方式

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]
测试:

>>> 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]

如果您只需要两个列表的笛卡尔乘积,则可以使用嵌套列表理解

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

如果您只需要两个列表的笛卡尔乘积,则可以使用嵌套列表理解

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

您始终可以使用中给出的代码


您始终可以使用中给出的代码


“你为什么要这么做?”彼得德格洛普只是好奇。为什么你要这么做?“彼得德格洛普只是好奇。哼哼,这是避免使用迭代工具的有趣方式。@ USER 309969.实际上:请考虑任何答案,如果它们帮助你,我得到这个错误:不支持的操作数类型(s)。对于*:'map'和'int'您要传递的参数是什么?我有这样的内容:我创建了上面的函数。。。然后,我做一个函数调用并在另一个函数中传递这样的函数:CyLyGys= [C1+C2为C1,C2在产品(D1x列,D2x列)],这是一个有趣的避免使用迭代工具的方法。@ USER 309969.实际上:请考虑任何答案,如果它们帮助您,我得到这个错误To:不支持的操作数类型(s)对于*:'map'和'int'您要传递的参数是什么?我有这样的内容:我创建了上面的函数。。。然后我执行一个函数调用,并在另一个函数中传递如下函数:col_groups=[c1+c2表示c1,c2表示乘积(d1_列,d2_列)]