如何基于opti数组更新嵌套字典数组list2中的指定val值?
问题:基于opti数组更新list2的for循环覆盖问题
需求说明
- 基于opti数组的值更新list2,逻辑:检查嵌套数组中是否存在含
'ind'键为指定值(如RSI_15)的字典,更新同一数组中含'val'键的字典的值。
当前问题
现有代码运行输出:
[['random', {'ind': 'RSI_15'}, {'cond': '<'}, {'val': 1000}], ['random', {'ind': 'volume'}, {'cond': '>'}, {'val': 1000}]]
存在for循环覆盖问题,期望输出:
[['random', {'ind': 'RSI_15'}, {'cond': '<'}, {'val': 15}], ['random', {'ind': 'volume'}, {'cond': '>'}, {'val': 1000}]]
现有代码
list2 = [['random', {'ind': 'RSI_15'}, {'cond': '<'}, {'val': 12}], ['random', {'ind': 'volume'}, {'cond': '>'}, {'val': 44}]] opti = [['RSI_15', 15], ['volume', 1000]] def update_val(indicator, val, values): flag = False for v in values: if isinstance(v, dict) and flag == False: try: v['ind'] = indicator flag = True except: continue if isinstance(v, dict) and flag == True: try: if v['val'] : v['val'] = val flag = True except: continue def up(conds, opti_val): for cond in conds: for item in opti_val: update_val(item[0], item[1], cond) return conds list2 = up(list2, opti) print(list2)
问题分析
原代码核心问题:
up函数中每个子数组会遍历所有opti元素,导致先更新RSI_15的val为15后,又被volume的遍历操作错误覆盖为1000。update_val逻辑混乱:未先判断子数组的ind是否匹配目标值就直接修改ind,flag的使用逻辑错误,导致只要进入分支就强制修改val。
修正后的代码
list2 = [['random', {'ind': 'RSI_15'}, {'cond': '<'}, {'val': 12}], ['random', {'ind': 'volume'}, {'cond': '>'}, {'val': 44}]] opti = [['RSI_15', 15], ['volume', 1000]] def update_val(target_ind, new_val, sub_array): # 定位当前子数组中的ind字典和val字典 ind_dict = None val_dict = None for elem in sub_array: if isinstance(elem, dict): if 'ind' in elem and elem['ind'] == target_ind: ind_dict = elem elif 'val' in elem: val_dict = elem # 匹配成功才更新val if ind_dict and val_dict: val_dict['val'] = new_val def up(conds, opti_val): # 将opti转为字典,快速查找对应值 opti_map = {ind: val for ind, val in opti_val} for cond in conds: # 获取当前子数组的ind值 current_ind = None for elem in cond: if isinstance(elem, dict) and 'ind' in elem: current_ind = elem['ind'] break # 仅当当前ind在opti中有对应值时执行更新 if current_ind in opti_map: update_val(current_ind, opti_map[current_ind], cond) return conds list2 = up(list2, opti) print(list2)
代码说明
- opti转字典:将opti数组转换为
{指标: 值}的键值对结构,避免重复遍历,提升匹配效率。 - 精准匹配更新:每个子数组先获取自身的
ind值,仅在opti中存在对应值时才触发更新,彻底解决循环覆盖问题。 - 逻辑清晰化:
update_val先分别定位目标字典,确认匹配后再更新val,避免原代码中flag的混乱逻辑。
内容的提问来源于stack exchange,提问作者Soma Juice
相关产品推荐
相关产品推荐

