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

如何用变量n指定Python itertools.product的多重复列表参数

解决itertools.product参数个数由变量n控制的问题

你之前的写法itertools.product([A]*n)无效的原因是:你把包含n个A的列表当成了单个参数传给product,但product需要的是多个可迭代对象作为独立的位置参数。

正确的做法是用Python的参数解包语法(在可迭代对象前加*),把列表里的每个A拆成独立参数传入:

import itertools

A = [1, 2, 3]
n = 3  # 可替换为任意需要的数值
cartesian_product = itertools.product(*[A] * n)

# 遍历查看生成的笛卡尔积
for combo in cartesian_product:
    print(combo)

当n=3时,*[A]*3等价于手动传入A, A, A,和itertools.product(A, A, A)的效果完全一致,会生成所有长度为3的笛卡尔积元组。

内容的提问来源于stack exchange,提问作者Silly Goose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:09:52