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

Python多列表组合生成:如何从三个列表生成指定组合列表

实现多列表笛卡尔积生成目标组合列表的方法

嘿,你要的其实就是生成多个列表的笛卡尔积,Python里有好几种简单的实现方式,我给你整理两个最常用的:

方法一:使用标准库itertools.product(推荐)

这是Python官方提供的最简洁高效的方式,专门用来处理这种笛卡尔积需求:

import itertools

# 定义你的三个列表
group1 = ['A', 'B', 'C']
group2 = [1]
group3 = ['x', 'y']

# 生成笛卡尔积并转换为列表的列表
final_result = [list(combination) for combination in itertools.product(group1, group2, group3)]
print(final_result)

运行这段代码就会直接输出你要的:[['A', 1, 'x'], ['A', 1, 'y'], ['B', 1, 'x'], ['B', 1, 'y'], ['C', 1, 'x'], ['C', 1, 'y']]

小提示:如果你的列表数量不固定(比如以后可能加更多列表),可以把所有列表放到一个大列表里,用*解包传入:

all_groups = [group1, group2, group3]
final_result = [list(c) for c in itertools.product(*all_groups)]

方法二:手动嵌套循环(适合理解原理)

如果不想用标准库,或者想自己实现逻辑加深理解,三层嵌套循环就能搞定:

group1 = ['A', 'B', 'C']
group2 = [1]
group3 = ['x', 'y']

final_result = []
# 依次遍历每个列表的元素,组合后加入结果
for item1 in group1:
    for item2 in group2:
        for item3 in group3:
            final_result.append([item1, item2, item3])

print(final_result)

这个方法逻辑很直观,就是把每个列表的元素挨个组合一遍,结果和上面完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:27:42