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

如何将嵌套列表或字典值转为可迭代对象传入itertools.product

使用itertools.product处理可变参数的解决方案

处理嵌套列表参数

Python提供的星号(*)解包语法可以直接将嵌套列表拆分为独立的位置参数传入itertools.product,无需额外转换:

import itertools

# 可变长度的嵌套列表
nested_input = [[1,3,4],[2,3,6],[9,4]]
# 解包后传入
for item in itertools.product(*nested_input):
    print(item)

运行后输出的结果和固定参数调用的输出完全一致。

直接处理值为列表的字典

无需先转换为嵌套列表,直接对字典的values()视图解包即可传入:

import itertools

# 值为列表的字典
dict_input = {
    "key1": [1,3,4],
    "key2": [2,3,6],
    "key3": [9,4]
}

# 直接解包values()传入
for item in itertools.product(*dict_input.values()):
    print(item)

补充说明

  1. Python 3.7及以上版本默认保留字典的插入顺序,解包后的参数顺序和字典键的插入顺序一致;如果你使用更早的Python版本且对参数顺序有要求,可以先对字典项按键排序后再取值:
# 按键排序保证参数顺序固定
sorted_values = [value for key, value in sorted(dict_input.items())]
for item in itertools.product(*sorted_values):
    print(item)
  1. 如果需要返回的笛卡尔积结果和原字典的键对应,可直接生成结构化的字典列表:
result = [dict(zip(dict_input.keys(), item)) for item in itertools.product(*dict_input.values())]

这样得到的每个结果元素都是和原字典键对应的字典,方便后续直接使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:45:02