python - Python 中单个列表上的 n 折笛卡尔积

标签 python cartesian-product

<分区>

如何在 Python 中以优雅(简洁)的方式计算列表中的 n 次笛卡尔积,即 A × ... × A(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_prod(l, n):
    if n == 0:
        return []  # compute the result for n = 0
    # preliminarily, create a list of lists instead of a list of tuples
    res = [[x] for x in l]  # initialize list with singleton tuples (n = 1)
    for i in range(n-1):
        res = [r + [x] for r in res for x in l]  # concatenate each n-1 tuple with each element from a
    res = [tuple(el) for el in res]  # turn the list of lists into a list of tuples
    return res

这段代码可以完成工作,但是是否有更短的、可能是一行的定义,可能是嵌套列表理解或 lambda 表达式?我对更紧凑的解决方案感兴趣,不一定是更具可读性的解决方案。


这个问题不是 Get the cartesian product of a series of lists? 的重复问题.我不希望一系列列表的笛卡尔积相互交叉。我想要单个列表的笛卡尔积与其自身交叉 n 次,其中 n 是提供给函数的参数。

最佳答案

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

这也适用于多个可迭代对象。

# 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')]

关于python - Python 中单个列表上的 n 折笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62418012/

相关文章:

python - 有没有办法使用 python 3.x 访问 Protocol Buffer ?

python - 逆笛卡尔积 - 给定乘积,找到索引

matlab - 将参数(即笛卡尔积)排列成多维数组

python - Django - 全局修改用户对象的字符串表示(甚至在管理之外)以在模型表单中使用

python - 带提示数据集的 KNN

python - Python 中的简单登录函数

python - 未安装 web2py Tk 库

sql - 混合隐式和显式 JOIN

python - 生成密码列表时出现内存错误

C++如何生成n维元组的笛卡尔积集