gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:37:23 25 4
gpt4 key购买 nike

<分区>

如何在 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 是提供给函数的参数。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com