You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中是否有符合DRY原则的方法生成n次笛卡尔积?

如何为同一列表生成长度为n的笛卡尔积

你可以利用itertools.product的repeat参数来解决这个问题,无需重复传入同一个列表,完美符合DRY原则。

示例代码

from itertools import product

def generate_n_dimensional_prods(in_list, n):
    return list(product(in_list, repeat=n))

使用示例

  • 当in_list = ['a', 'b', 'c']且n=2时,调用函数返回:
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]

和你之前的函数结果完全一致,但现在可以灵活调整维度n。

  • 当n=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')]

原理说明

product函数的repeat参数用于指定输入序列需要被重复的次数,等价于将同一序列多次作为参数传入。比如product(in_list, repeat=3)和product(in_list, in_list, in_list)效果完全相同,但前者更简洁易维护。

内容的提问来源于stack exchange,提问作者James Geddes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:32:07