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

Python循环为字典列表赋值Datetime对象异常问题排查

问题分析与修复

核心问题

你遇到的问题本质是**schedule_items_final列表中的元素可能存在重复引用同一个字典对象的情况**,再加上循环遍历的方式导致赋值逻辑出现混淆:

  1. 当你用for schedule_item_final in schedule_items_final遍历列表时,每次拿到的schedule_item_final是列表元素的引用;
  2. 同时手动维护counter索引修改元素,如果列表中多个元素指向同一个字典,后续赋值会覆盖之前的修改,最终除第一个元素外,其余元素的start_datetime都会被最后一次赋值覆盖;
  3. 手动计数的方式也容易出现索引偏移,进一步放大了逻辑混乱。

修复代码

改用enumerate同时获取索引和元素,直接操作当前元素,避免手动维护计数器,同时确保每个元素的修改独立:

# 重新计算开始和结束Datetime
current_datetime = self.start_datetime
for idx, item in enumerate(schedule_items_final):
    # datetime是不可变类型,无需deepcopy,直接赋值即可
    item["start_datetime"] = current_datetime
    duration_seconds = item["duration_milliseconds"] / 1000
    item["end_datetime"] = current_datetime + timedelta(seconds=duration_seconds)
    current_datetime += timedelta(seconds=duration_seconds)
    print(current_datetime)
        
for item in schedule_items_final:
    print(item["start_datetime"])

关键注意事项

  1. 检查列表初始化逻辑:确保schedule_items_final中的每个元素都是独立的字典对象。如果是通过[shared_dict] * n创建的列表,所有元素会引用同一个字典,修改任意元素都会影响其他元素,正确的初始化方式应为[{} for _ in range(n)];
  2. 避免不必要的deepcopy:datetime是不可变类型,直接赋值不会导致引用共享问题,去掉copy.deepcopy可以提升代码效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:07:33