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

Python中for循环创建字典追加至列表仅保留单个的问题

问题分析与解决方案

问题根源

  1. 循环内重复初始化列表:你在for循环内部每次都执行dicts = [],这会导致每次循环都把列表重置为空,最终只保留最后一次追加的字典。
  2. 全局变量的不良使用:用global d传递字典属于冗余写法,容易引发变量污染,增加代码维护难度。

修复方案(推荐写法)

调整函数逻辑,让函数直接返回生成的字典,并将列表初始化移到循环外部:

# !pip install sorcery
from sorcery import dict_of

def ic_strategy_2(first, second, third, fourth):
    risk_reward_ratio = 10
    max_profit = 20
    nf_wed_range_pct = 30
    return dict_of(risk_reward_ratio, max_profit, nf_wed_range_pct)

lst = [[300,150,50,50],[200,300,50,50],[250,250,50,50]]
dicts = []  # 列表初始化移到循环外,仅执行一次
for item in lst:
    result_dict = ic_strategy_2(*item)
    dicts.append(result_dict)

print(dicts)

极简修复(不修改函数结构)

如果不想改动函数,仅调整循环逻辑即可:

# !pip install sorcery
from sorcery import dict_of

def ic_strategy_2(first,second,third,fourth):
    global d
    risk_reward_ratio = 10
    max_profit = 20
    nf_wed_range_pct = 30
    d = dict_of(risk_reward_ratio,max_profit ,nf_wed_range_pct)

lst = [[300,150,50,50],[200,300,50,50],[250,250,50,50]]
dicts = []  # 移到循环外部
for item in lst:
    ic_strategy_2(*item)
    dicts.append(d)

print(dicts)

输出结果

运行后会得到预期的3个字典组成的列表:

[{'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10}, {'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10}, {'max_profit': 20, 'nf_wed_range_pct': 30, 'risk_reward_ratio': 10}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:36:17