Python中单个列表上的n倍笛卡尔乘积

Python中单个列表上的n倍笛卡尔乘积,python,cartesian-product,Python,Cartesian Product,如何计算列表上的n次笛卡尔积,即a×。。。×n次,在Pyton中以优雅简洁的方式 这个问题不是重复的。我不希望一系列列表的笛卡尔乘积相互交叉。我想要一个单列表的笛卡尔积与它自身相交n次,其中n是给定给函数的一个参数 示例: l = ["a", "b", "c"] > cart_prod(l, 0) [] > cart_prod(l, 1) [('a',), ('b',), ('c',)] > cart_prod(l, 2) [('a', 'a'), ('a', 'b'), ('

如何计算列表上的n次笛卡尔积,即a×。。。×n次,在Pyton中以优雅简洁的方式

这个问题不是重复的。我不希望一系列列表的笛卡尔乘积相互交叉。我想要一个单列表的笛卡尔积与它自身相交n次,其中n是给定给函数的一个参数

示例:

l = ["a", "b", "c"]
> cart_prod(l, 0)
[]
> cart_prod(l, 1)
[('a',), ('b',), ('c',)]
> cart_prod(l, 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
> cart_prod(l, 3)
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]
我提出了以下迭代解决方案:

def cart_产品,n: 如果n==0: return[]计算n=0的结果 首先,创建一个列表列表,而不是元组列表 res=[[x]表示l中的x]使用单元组n=1初始化列表 对于rangen-1中的i: res=[r+[x]表示r在res中表示x在l中表示]将每个n-1元组与 res=[tupleel for el in res]将列表列表转换为元组列表 返回res 这段代码完成了这项工作,但是是否有一个更短的、可能只有一行的定义,可能是嵌套的列表理解或lambda表达式?我对更简洁的解决方案感兴趣,而不一定是可读性更强的解决方案。

itertools.product使用关键字参数来指示应重复给定的参数

>>> from itertools import product
>>> list(product([1,2], repeat=0))
[()]
>>> list(product([1,2], repeat=1))
[(1,), (2,)]
>>> list(product([1,2], repeat=2))
[(1, 1), (1, 2), (2, 1), (2, 2)]
这也适用于多个iTerable

# Equivalent to list(product([1,2], ['a', 'b'], [1,2], ['a', 'b']))
>>> list(product([1,2], ['a', 'b'], repeat=2))
[(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'), (1, 'a', 2, 'b'), (1, 'b', 1, 'a'), (1, 'b', 1, 'b'), (1, 'b', 2, 'a'), (1, 'b', 2, 'b'), (2, 'a', 1, 'a'), (2, 'a', 1, 'b'), (2, 'a', 2, 'a'), (2, 'a', 2, 'b'), (2, 'b', 1, 'a'), (2, 'b', 1, 'b'), (2, 'b', 2, 'a'), (2, 'b', 2, 'b')]
itertools.product使用关键字参数来指示应重复给定的参数

>>> from itertools import product
>>> list(product([1,2], repeat=0))
[()]
>>> list(product([1,2], repeat=1))
[(1,), (2,)]
>>> list(product([1,2], repeat=2))
[(1, 1), (1, 2), (2, 1), (2, 2)]
这也适用于多个iTerable

# Equivalent to list(product([1,2], ['a', 'b'], [1,2], ['a', 'b']))
>>> list(product([1,2], ['a', 'b'], repeat=2))
[(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'), (1, 'a', 2, 'b'), (1, 'b', 1, 'a'), (1, 'b', 1, 'b'), (1, 'b', 2, 'a'), (1, 'b', 2, 'b'), (2, 'a', 1, 'a'), (2, 'a', 1, 'b'), (2, 'a', 2, 'a'), (2, 'a', 2, 'b'), (2, 'b', 1, 'a'), (2, 'b', 1, 'b'), (2, 'b', 2, 'a'), (2, 'b', 2, 'b')]

在我看来,它仍然像一个复制品。只需复制列表,然后使用itertools.product。更好的是,itertools.tee列表n次,然后使用itertools.product。@bnaecker您不需要tee。@chepner Nice,我以前从未使用过kwarg。它在我看来仍然是重复的。只需复制列表,然后使用itertools.product。更好的是,itertools.tee列表n次,然后使用itertools.product。@bnaecker您不需要tee。@chepner Nice,我以前从未使用过那个kwarg。