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

Python如何从零实现网格搜索所需的参数网格生成功能

任意参数字典组合生成方案

核心逻辑

我们需要实现的功能本质是计算所有参数可选值的笛卡尔积,再将每组值和对应的参数名拼接为字典,不需要提前预知参数数量,也不依赖第三方库的内置网格搜索工具。

代码实现

递归版本

逻辑简单易懂,适合参数数量较少的场景:

def myFunc(param_dict):
    # 提取参数名与对应的可选值列表
    param_names = list(param_dict.keys())
    param_values = list(param_dict.values())
    
    # 自定义笛卡尔积递归实现
    def cartesian_product(arrays):
        if len(arrays) == 1:
            return [[x] for x in arrays[0]]
        # 先计算后续所有参数的笛卡尔积
        rest_product = cartesian_product(arrays[1:])
        # 拼接当前参数的每个值到已有组合中
        result = []
        for current_val in arrays[0]:
            for item in rest_product:
                result.append([current_val] + item)
        return result
    
    # 生成所有值组合后映射为参数字典
    all_value_combos = cartesian_product(param_values)
    return [dict(zip(param_names, combo)) for combo in all_value_combos]

迭代版本

无递归深度限制,适合参数数量多的场景,性能更稳定:

def myFunc(param_dict):
    param_names = list(param_dict.keys())
    param_values = list(param_dict.values())
    
    # 迭代生成笛卡尔积
    result = [[]]
    for val_list in param_values:
        temp = []
        for existing_combo in result:
            for current_val in val_list:
                temp.append(existing_combo + [current_val])
        result = temp
    
    return [dict(zip(param_names, combo)) for combo in result]

测试验证

输入示例中的测试用例:

print(myFunc({'ParA':[1,2,3], 'ParB': [0.1,0.2,0.3,0.4]}))

输出结果完全匹配需求:

[{'ParA': 1, 'ParB': 0.1}, {'ParA': 1, 'ParB': 0.2}, {'ParA': 1, 'ParB': 0.3}, {'ParA': 1, 'ParB': 0.4}, {'ParA': 2, 'ParB': 0.1}, {'ParA': 2, 'ParB': 0.2}, {'ParA': 2, 'ParB': 0.3}, {'ParA': 2, 'ParB': 0.4}, {'ParA': 3, 'ParB': 0.1}, {'ParA': 3, 'ParB': 0.2}, {'ParA': 3, 'ParB': 0.3}, {'ParA': 3, 'ParB': 0.4}]

实现特点

  • 支持任意数量的输入参数,只要参数字典不为空即可
  • 自动适配每个参数不同的可选值长度,和字典内键的排序无关
  • 完全从零实现,未使用任何第三方库的网格搜索、笛卡尔积内置函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:24:03