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

如何以Pythonic方式生成笛卡尔积形式的嵌套列表?

生成指定组合列表的Pythonic写法

你需要生成的是给定列表的笛卡尔积,完全可以用Python标准库中的itertools.product来实现,避免嵌套多层for循环,写法简洁且符合Python风格。

需求回顾

给定列表:

given_list = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # 每个子列表为range(0, n),共m个这样的子列表

需要生成的目标列表(所有m元组合,总数为n^m):

new_list = [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], ..., [2, 2, 2]]

实现代码

import itertools

given_list = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
# 解包given_list的子列表作为product的参数,再将每个元组结果转为列表
new_list = [list(combination) for combination in itertools.product(*given_list)]

代码说明

  • itertools.product(*given_list):*操作符会把given_list中的每个子列表单独作为参数传入product,该函数会生成所有可能的元素组合(返回迭代器,每个元素是元组类型)
  • 列表推导式[list(...) for ...]:将迭代器中的每个元组转换为列表,最终得到目标的嵌套列表结构

扩展场景

如果你的given_list中的子列表元素不统一(比如given_list = [[0,1], [2,3], [4,5]]),这个方法同样适用,会生成所有跨子列表的元素组合,总数为各子列表长度的乘积。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:20:43