【问题标题】:Get the cartesian product of a series of lists?得到一系列列表的笛卡尔积?
【发布时间】:2025-12-28 07:05:11
【问题描述】:

如何从一组列表中获取笛卡尔积(所有可能的值组合)?

输入:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

期望的输出:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]

【问题讨论】:

  • 请注意,“所有可能的组合”与“笛卡尔积”并不完全相同,因为在笛卡尔积中,允许重复。
  • 有没有不重复的笛卡尔积?
  • @KJW 是的,set(cartesian product)
  • 笛卡尔积中不应有重复项,除非输入列表本身包含重复项。如果您希望笛卡尔积中没有重复项,请在所有输入列表中使用 set(inputlist)。不在结果上。
  • 在数学上,笛卡尔积是一个集合,因此笛卡尔积包含重复项。另一方面,如果输入有重复,itertools.product 将在输出中有重复。所以itertools.product 严格来说不是笛卡尔积,除非你将输入包装在@CamilB 中提到的set

标签: python list cartesian-product


【解决方案1】:

列表推导简单明了:

import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
lst = [i for i in itertools.product(*somelists)]

【讨论】:

    【解决方案2】:

    这是可以做到的

    [(x, y) for x in range(10) for y in range(10)]
    

    另一个变量?没问题:

    [(x, y, z) for x in range(10) for y in range(10) for z in range(10)]
    

    【讨论】:

      【解决方案3】:

      以下代码是Using numpy to build an array of all combinations of two arrays 的 95 % 复制,所有学分都在那里!据说这要快得多,因为它仅在 numpy 中。

      import numpy as np
      
      def cartesian(arrays, dtype=None, out=None):
          arrays = [np.asarray(x) for x in arrays]
          if dtype is None:
              dtype = arrays[0].dtype
          n = np.prod([x.size for x in arrays])
          if out is None:
              out = np.zeros([n, len(arrays)], dtype=dtype)
      
          m = int(n / arrays[0].size) 
          out[:,0] = np.repeat(arrays[0], m)
          if arrays[1:]:
              cartesian(arrays[1:], out=out[0:m, 1:])
              for j in range(1, arrays[0].size):
                  out[j*m:(j+1)*m, 1:] = out[0:m, 1:]
          return out
      

      如果您不想从所有条目的第一个条目中获取 dtype,则需要将 dtype 定义为参数。如果您有字母和数字作为项目,请使用 dtype = 'object'。测试:

      somelists = [
         [1, 2, 3],
         ['a', 'b'],
         [4, 5]
      ]
      
      [tuple(x) for x in cartesian(somelists, 'object')]
      

      输出:

      [(1, 'a', 4),
       (1, 'a', 5),
       (1, 'b', 4),
       (1, 'b', 5),
       (2, 'a', 4),
       (2, 'a', 5),
       (2, 'b', 4),
       (2, 'b', 5),
       (3, 'a', 4),
       (3, 'a', 5),
       (3, 'b', 4),
       (3, 'b', 5)]
      

      【讨论】:

        【解决方案4】:

        提前拒绝:

        def my_product(pools: List[List[Any]], rules: Dict[Any, List[Any]], forbidden: List[Any]) -> Iterator[Tuple[Any]]:
            """
            Compute the cartesian product except it rejects some combinations based on provided rules
            
            :param pools: the values to calculate the Cartesian product on 
            :param rules: a dict specifying which values each value is incompatible with
            :param forbidden: values that are never authorized in the combinations
            :return: the cartesian product
            """
            if not pools:
                return
        
            included = set()
        
            # if an element has an entry of 0, it's acceptable, if greater than 0, it's rejected, cannot be negative
            incompatibles = defaultdict(int)
            for value in forbidden:
                incompatibles[value] += 1
            selections = [-1] * len(pools)
            pool_idx = 0
        
            def current_value():
                return pools[pool_idx][selections[pool_idx]]
        
            while True:
                # Discard incompatibilities from value from previous iteration on same pool
                if selections[pool_idx] >= 0:
                    for value in rules[current_value()]:
                        incompatibles[value] -= 1
                    included.discard(current_value())
        
                # Try to get to next value of same pool
                if selections[pool_idx] != len(pools[pool_idx]) - 1:
                    selections[pool_idx] += 1
                # Get to previous pool if current is exhausted
                elif pool_idx != 0:
                    selections[pool_idx] = - 1
                    pool_idx -= 1
                    continue
                # Done if first pool is exhausted
                else:
                    break
        
                # Add incompatibilities of newly added value
                for value in rules[current_value()]:
                    incompatibles[value] += 1
                included.add(current_value())
        
                # Skip value if incompatible
                if incompatibles[current_value()] or \
                        any(intersection in included for intersection in rules[current_value()]):
                    continue
        
                # Submit combination if we're at last pool
                if pools[pool_idx] == pools[-1]:
                    yield tuple(pool[selection] for pool, selection in zip(pools, selections))
                # Else get to next pool
                else:
                    pool_idx += 1
        

        我有a case,我必须在其中获取一个非常大的笛卡尔积的第一个结果。尽管我只想要一件物品,但这需要很长时间。问题在于,由于结果的顺序,它必须遍历许多不需要的结果才能找到正确的结果。因此,如果我有 10 个包含 50 个元素的列表,并且前两个列表的第一个元素不兼容,它必须遍历最后 8 个列表的笛卡尔积,尽管它们都会被拒绝。

        此实现可以在结果包含每个列表中的一项之前对其进行测试。因此,当我检查某个元素与之前列表中已包含的元素不兼容时,我会立即转到当前列表的下一个元素,而不是遍历以下列表的所有产品。

        【讨论】:

          【解决方案5】:

          您可以使用标准库中的itertools.product 来获取笛卡尔积。 itertools 中其他很酷的相关实用程序包括 permutationscombinationscombinations_with_replacement。这是a link 到下面sn-p 的python 代码笔:

          from itertools import product
          
          somelists = [
             [1, 2, 3],
             ['a', 'b'],
             [4, 5]
          ]
          
          result = list(product(*somelists))
          print(result)
          

          【讨论】:

            【解决方案6】:

            itertools.product

            可从 Python 2.6 获得。

            import itertools
            
            somelists = [
               [1, 2, 3],
               ['a', 'b'],
               [4, 5]
            ]
            for element in itertools.product(*somelists):
                print(element)
            

            与,

            for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
                print(element)
            

            【讨论】:

            • 如果您使用 OP 提供的变量 somelists,则只需要添加“*”字符。
            • somelists前*有什么用?它有什么作用?
            • @VineetKumarDoshi:这里它用于将列表解压缩为函数调用的多个参数。在这里阅读更多:*.com/questions/36901/…
            • 注意:这仅在每个列表包含至少一项时才有效
            • @igo 它也适用于任何列表包含零项——至少一个零大小列表和任何其他列表的笛卡尔积一个空列表,这正是这会产生什么。
            【解决方案7】:

            我相信这行得通:

            def cartesian_product(L):  
               if L:
                   return {(a,) + b for a in L[0] 
                                    for b in cartesian_product(L[1:])}
               else:
                   return {()}
            

            【讨论】:

              【解决方案8】:

              巨石阵方法:

              def giveAllLists(a, t):
                  if (t + 1 == len(a)):
                      x = []
                      for i in a[t]:
                          p = [i]
                          x.append(p)
                      return x
                  x = []
              
                  out = giveAllLists(a, t + 1)
                  for i in a[t]:
              
                      for j in range(len(out)):
                          p = [i]
                          for oz in out[j]:
                              p.append(oz)
                          x.append(p)
                  return x
              
              xx= [[1,2,3],[22,34,'se'],['k']]
              print(giveAllLists(xx, 0))
              
              
              

              输出:

              [[1, 22, 'k'], [1, 34, 'k'], [1, 'se', 'k'], [2, 22, 'k'], [2, 34, 'k'], [2, 'se', 'k'], [3, 22, 'k'], [3, 34, 'k'], [3, 'se', 'k']]
              

              【讨论】:

                【解决方案9】:

                递归方法:

                def rec_cart(start, array, partial, results):
                  if len(partial) == len(array):
                    results.append(partial)
                    return 
                
                  for element in array[start]:
                    rec_cart(start+1, array, partial+[element], results)
                
                rec_res = []
                some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]  
                rec_cart(0, some_lists, [], rec_res)
                print(rec_res)
                

                迭代方法:

                def itr_cart(array):
                  results = [[]]
                  for i in range(len(array)):
                    temp = []
                    for res in results:
                      for element in array[i]:
                        temp.append(res+[element])
                    results = temp
                
                  return results
                
                some_lists = [[1, 2, 3], ['a', 'b'], [4, 5]]  
                itr_res = itr_cart(some_lists)
                print(itr_res)
                

                【讨论】:

                  【解决方案10】:

                  对上述递归生成器解决方案的小修改:

                  def product_args(*args):
                      if args:
                          for a in args[0]:
                              for prod in product_args(*args[1:]) if args[1:] else ((),):
                                  yield (a,) + prod
                  

                  当然还有一个包装器,使它的工作方式与该解决方案完全相同:

                  def product2(ar_list):
                      """
                      >>> list(product(()))
                      [()]
                      >>> list(product2(()))
                      []
                      """
                      return product_args(*ar_list)
                  

                  with 一个权衡:它检查递归是否应该在每个外部循环上中断,并且一个增益:空调用时没有收益,例如product(()),我想在语义上会更正确(参见文档测试)。

                  关于列表推导:数学定义适用于任意数量的参数,而列表推导只能处理已知数量的参数。

                  【讨论】:

                    【解决方案11】:

                    虽然已经有很多答案了,但还是想分享一下我的一些想法:

                    迭代方法

                    def cartesian_iterative(pools):
                      result = [[]]
                      for pool in pools:
                        result = [x+[y] for x in result for y in pool]
                      return result
                    

                    递归方法

                    def cartesian_recursive(pools):
                      if len(pools) > 2:
                        pools[0] = product(pools[0], pools[1])
                        del pools[1]
                        return cartesian_recursive(pools)
                      else:
                        pools[0] = product(pools[0], pools[1])
                        del pools[1]
                        return pools
                    def product(x, y):
                      return [xx + [yy] if isinstance(xx, list) else [xx] + [yy] for xx in x for yy in y]
                    

                    Lambda 方法

                    def cartesian_reduct(pools):
                      return reduce(lambda x,y: product(x,y) , pools)
                    

                    【讨论】:

                    • 在“迭代方法”中,为什么将结果声明为 result = [[]] 我知道它是 list_of_list 但通常即使我们声明 list_of_list 我们使用 [] 而不是 [[]]
                    • 我对 Pythonic 解决方案有点陌生。请您或某些路人在单独的循环中以“迭代方法”编写列表理解吗?
                    • @SachinS 您在外部列表中使用内部列表,因为您遍历外部列表(对于结果中的 x),内部列表意味着外部列表不为空。如果它为空,则不会发生迭代,因为“结果”中没有 x。然后您将项目添加到该列表中。该示例几乎取自官方文档,但我敢说它比显式更隐含。如果你将它重构为仅基于循环的代码并删除理解,就像 Johny Boy 所说的那样,那将需要更多的代码。
                    • 什么是pools?它是我想要产品的列表的列表吗?
                    【解决方案12】:

                    在 Python 2.6 及更高版本中,您可以使用“itertools.product”。在旧版本的 Python 中,您可以使用以下(几乎——参见文档)等效的 code from the documentation,至少作为起点:

                    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)
                    

                    两者的结果都是一个迭代器,所以如果你真的需要一个列表进行进一步处理,请使用list(result)

                    【讨论】:

                    • 根据文档,实际的 itertools.product 实现不会构建中间结果,这可能会很昂贵。对于中等大小的列表,使用这种技术可能会很快失控。
                    • 我只能将 OP 指向文档,而不是为他阅读。
                    • 文档中的代码旨在演示产品功能的作用,而不是作为 Python 早期版本的解决方法。
                    【解决方案13】:

                    我会使用列表理解:

                    somelists = [
                       [1, 2, 3],
                       ['a', 'b'],
                       [4, 5]
                    ]
                    
                    cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]
                    

                    【讨论】:

                    • 我真的很喜欢这个使用列表推导的解决方案。不知道为什么不被更多人点赞,就是这么简单。
                    • @llekn 因为代码似乎固定为列表的数量
                    • @Bằng Rikimaru 如何修复列表理解? lst = [i for i in itertools.product(*somelists)]
                    【解决方案14】:

                    只是补充一点已经说过的内容:如果您使用 sympy,则可以使用符号而不是字符串,这使得它们在数学上很有用。

                    import itertools
                    import sympy
                    
                    x, y = sympy.symbols('x y')
                    
                    somelist = [[x,y], [1,2,3], [4,5]]
                    somelist2 = [[1,2], [1,2,3], [4,5]]
                    
                    for element in itertools.product(*somelist):
                      print element
                    

                    关于sympy

                    【讨论】:

                      【解决方案15】:

                      这是一个递归生成器,它不存储任何临时列表

                      def product(ar_list):
                          if not ar_list:
                              yield ()
                          else:
                              for a in ar_list[0]:
                                  for prod in product(ar_list[1:]):
                                      yield (a,)+prod
                      
                      print list(product([[1,2],[3,4],[5,6]]))
                      

                      输出:

                      [(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
                      

                      【讨论】:

                      • 不过,它们存储在堆栈中。
                      • @QuentinPradet 你的意思是像def f(): while True: yield 1 这样的生成器会在我们处理它时继续增加它的堆栈大小吗?
                      • @QuentinPradet 是的,但即使在这种情况下,也只有最大深度所需的堆栈,而不是整个列表,所以在这种情况下堆栈为 3
                      • 这是真的,对不起。基准可能很有趣。 :)
                      【解决方案16】:

                      itertools.product:

                      import itertools
                      result = list(itertools.product(*somelists))
                      

                      【讨论】:

                      • somelists前*有什么用?
                      • @VineetKumarDoshi "product(somelists)" 是子列表之间的笛卡尔积,Python 首先得到 "[1, 2, 3]" 作为一个元素,然后在下一个 comman 之后获取其他元素,即换行符,因此第一个乘积项是 ([1, 2, 3],),类似于第二个 ([4, 5],) 等等 "[([1, 2, 3],), ([4, 5],), ([6, 7],)]".如果你想得到元组内元素之间的笛卡尔积,你需要用 Asterisk 告诉 Python 元组结构。对于字典,您使用 **。更多here.
                      【解决方案17】:

                      对于 Python 2.5 及更早版本:

                      >>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]]
                      [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
                       (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
                       (3, 'b', 4), (3, 'b', 5)]
                      

                      这是product() 的递归版本(只是一个插图):

                      def product(*args):
                          if not args:
                              return iter(((),)) # yield tuple()
                          return (items + (item,) 
                                  for items in product(*args[:-1]) for item in args[-1])
                      

                      例子:

                      >>> list(product([1,2,3], ['a','b'], [4,5])) 
                      [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
                       (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
                       (3, 'b', 4), (3, 'b', 5)]
                      >>> list(product([1,2,3]))
                      [(1,), (2,), (3,)]
                      >>> list(product([]))
                      []
                      >>> list(product())
                      [()]
                      

                      【讨论】:

                      • 如果某些args 是迭代器,则递归版本不起作用。
                      【解决方案18】:
                      import itertools
                      >>> for i in itertools.product([1,2,3],['a','b'],[4,5]):
                      ...         print i
                      ...
                      (1, 'a', 4)
                      (1, 'a', 5)
                      (1, 'b', 4)
                      (1, 'b', 5)
                      (2, 'a', 4)
                      (2, 'a', 5)
                      (2, 'b', 4)
                      (2, 'b', 5)
                      (3, 'a', 4)
                      (3, 'a', 5)
                      (3, 'b', 4)
                      (3, 'b', 5)
                      >>>
                      

                      【讨论】:

                      • 支持并鼓励对此答案的支持,这是最容易快速阅读和理解的答案。