通用变量生成函数开发需求:按grace_type匹配对应值
通用Grace变量生成函数实现方案
需求说明
需开发一个通用变量生成函数,传入
grace_type参数(如National、Continental、Rural等)后,可自动将Grace 1、Grace 2、Grace 3、Grace 4赋值为对应预设值。例如当grace_type=National时,四个变量值分别为2、2、6、9。
实现思路
采用配置映射表的方式,将不同grace_type对应的预设值集中管理,函数仅需根据传入参数匹配对应配置,即可快速生成目标变量。这种方式扩展性极强,新增类型无需修改核心逻辑,仅需补充配置即可。
代码示例(Python)
def generate_grace_vars(grace_type): # 预设配置表,可根据实际需求扩展更多类型 grace_presets = { "National": [2, 2, 6, 9], "Continental": [1, 3, 5, 8], # 示例值,请替换为实际预设 "Rural": [3, 3, 7, 10] # 示例值,请替换为实际预设 } # 校验输入参数合法性 if grace_type not in grace_presets: raise ValueError(f"Unsupported grace_type: {grace_type}") # 解构返回四个变量值,直接赋值即可使用 return grace_presets[grace_type] # 使用示例 grace_1, grace_2, grace_3, grace_4 = generate_grace_vars("National") print(grace_1, grace_2, grace_3, grace_4) # 输出:2 2 6 9
扩展说明
- 如果需要返回更具可读性的结构,可以将返回值改为字典:
return { "Grace 1": grace_presets[grace_type][0], "Grace 2": grace_presets[grace_type][1], "Grace 3": grace_presets[grace_type][2], "Grace 4": grace_presets[grace_type][3] } - 若使用其他编程语言(如JavaScript),逻辑完全一致,仅需调整语法:
function generateGraceVars(graceType) { const gracePresets = { "National": [2, 2, 6, 9], "Continental": [1, 3, 5, 8], "Rural": [3, 3, 7, 10] }; if (!gracePresets.hasOwnProperty(graceType)) { throw new Error(`Unsupported grace_type: ${graceType}`); } return gracePresets[graceType]; } // 使用示例 const [grace1, grace2, grace3, grace4] = generateGraceVars("National");
内容的提问来源于stack exchange,提问作者codingr
相关产品推荐
相关产品推荐

