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

如何生成含元组的列表的笛卡尔积并得到列表嵌套结果?

解决笛卡尔积结果的嵌套类型问题

不需要自行实现for循环,只需对product返回的结果做简单转换即可:

itertools.product的默认行为是将每个笛卡尔积项以元组形式返回,而你需要的是列表形式。可以用列表推导式把每个元组转换为列表:

from itertools import product

listOfListsOfTuples = [ [(1,2),], [(3,4),(5,6)] ]
# 对product返回的每个元组转成列表
got = [list(item) for item in product(*listOfListsOfTuples)]
print('got   :', got)

wanted = [ [(1,2),(3,4)], [(1,2),(5,6)] ]
print('wanted:', wanted)

运行后输出会和wanted完全一致:

got   : [[(1, 2), (3, 4)], [(1, 2), (5, 6)]]
wanted: [[(1, 2), (3, 4)], [(1, 2), (5, 6)]]

这种方式既保留了product的高效性,又满足了你的格式需求,比手动写循环更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:27:12