获取一系列列表的笛卡尔积?

ʞɔı*_*ɔıu 289 python list cartesian-product

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

输入:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
Run Code Online (Sandbox Code Playgroud)

期望的输出:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...]
Run Code Online (Sandbox Code Playgroud)

Tri*_*ych 348

在Python 2.6+中

import itertools
for element in itertools.product(*somelists):
    print(element)
Run Code Online (Sandbox Code Playgroud)

文档: Python 3 - itertools.product

  • 如果您使用OP提供的变量some​​lists,只需要添加'*'字符. (21认同)
  • @igo当任何列表包含零个项目时它也可以工作——至少一个零大小的列表和任何其他列表的笛卡尔积*是*一个空列表,而这正是它产生的结果。 (7认同)
  • @VineetKumarDoshi:这里用于将列表解压缩到函数调用的多个参数中.点击此处了解更多信息:http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters (6认同)
  • 注意:仅当每个列表包含至少一个项目时,此方法才有效 (4认同)
  • 在某些列表之前有什么用?`` 它有什么作用? (2认同)
  • 只是一个细节,但请注意,“itertools.product()”还可以处理生成器,而不仅仅是类似列表的对象。 (2认同)

Jas*_*ker 76

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)
>>>
Run Code Online (Sandbox Code Playgroud)


jfs*_*jfs 34

对于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)]
Run Code Online (Sandbox Code Playgroud)

这是一个递归版本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])
Run Code Online (Sandbox Code Playgroud)

例:

>>> 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())
[()]
Run Code Online (Sandbox Code Playgroud)


Sil*_*ost 19

使用itertools.product:

import itertools
result = list(itertools.product(*somelists))
Run Code Online (Sandbox Code Playgroud)

  • 在某些列表之前有什么用?`` (6认同)

小智 14

我会使用列表理解:

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]]
Run Code Online (Sandbox Code Playgroud)

  • @llekn因为代码似乎固定为列表的数量 (12认同)

小智 11

在Python 2.6及更高版本中,您可以使用'itertools.product`.在旧版本的Python中,您可以使用以下(几乎 - 请参阅文档)文档中的等效代码,至少作为起点:

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)
Run Code Online (Sandbox Code Playgroud)

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

  • 我只能将OP指向文档,而不是为他阅读. (4认同)

Anu*_*yal 10

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

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]]))
Run Code Online (Sandbox Code Playgroud)

输出:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
Run Code Online (Sandbox Code Playgroud)

  • 不过,它们存储在堆栈中。 (2认同)

小智 7

虽然已有很多答案,但我想分享一下我的想法:

迭代方法

def cartesian_iterative(pools):
  result = [[]]
  for pool in pools:
    result = [x+[y] for x in result for y in pool]
  return result
Run Code Online (Sandbox Code Playgroud)

递归方法

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]
Run Code Online (Sandbox Code Playgroud)

Lambda方法

def cartesian_reduct(pools):
  return reduce(lambda x,y: product(x,y) , pools)
Run Code Online (Sandbox Code Playgroud)


Jai*_*Jai 7

递归方法:

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)
Run Code Online (Sandbox Code Playgroud)

迭代方法:

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)
Run Code Online (Sandbox Code Playgroud)