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

如何从嵌套列表中获取正确的itertools.product笛卡尔积结果?

解决Python嵌套列表的笛卡尔积问题

直接用星号(*)解包嵌套列表就能得到你想要的结果,具体写法如下:

from itertools import product

s = [[1,2,3], [4,5], [-1]]
print(list(product(*s)))

输出结果和你第一个示例完全一致:

[(1, 4, -1), (1, 5, -1), (2, 4, -1), (2, 5, -1), (3, 4, -1), (3, 5, -1)]

为什么之前的写法不对?

product(s)会把s这个列表本身当作唯一的可迭代参数,遍历s里的每个子列表并将其作为单独元素放进元组,所以得到[([1,2,3],), ([4,5],), ([-1],)]这种非预期结果。

而product(*s)是把s里的每个子列表分别作为独立参数传给product,等价于你最初写的product(a, b, c),这样就能正确生成所有元素的笛卡尔积。

备选方案(若不想用解包)

如果需要避免星号解包,也可以用functools.reduce逐步计算笛卡尔积:

from itertools import product
from functools import reduce

s = [[1,2,3], [4,5], [-1]]
# 先得到嵌套元组的结果
temp_result = list(reduce(lambda x, y: product(x, y), s))
# 展开嵌套的元组
final_result = [tuple(item for sub_tup in tup for item in sub_tup) for tup in temp_result]
print(final_result)

不过星号解包的写法更简洁直观,是首选方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:07:11