You need to enable JavaScript to run this app. Python嵌套循环生成字典异常:仅外层循环生效,内层波段遍历未执行
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套循环生成字典异常:仅外层循环生效,内层波段遍历未执行

Sentinel-2影像检索循环异常排查与修复

问题根因

1. 可变对象引用污染

Python字典属于可变对象,直接赋值传递的是内存引用而非值拷贝

  • 原代码中data = {}定义在外层循环外部,所有影像条目共用同一个字典内存地址
  • 执行downloads[i] = data时,仅将字典的引用存入downloads,而非生成独立的字典副本
  • 后续循环对data的修改会直接覆盖之前存储的所有条目,最终downloads中所有键对应的内容都是最后一次循环的结果,结合JSON渲染逻辑,容易被误判为仅返回了第一个影像条目

2. 内层波段循环中断诱因

  • 原代码无异常捕获,若波段资产调用抛出KeyError(如satsearch版本不兼容资产访问方式、当前条目缺失指定波段),会直接中断内层循环,导致波段链接未被写入data
  • 旧版satsearch的波段资产需通过item.assets[band]访问,item.asset(band)为新版API,版本不匹配时会返回空值触发异常

修复后可运行代码

from satsearch import Search
from IPython.display import JSON

# 配置参数
url = 'https://earth-search.aws.element84.com/v0'
collection = 'sentinel-s2-l2a-cogs'
startDate = '2021-01-01'
endDate = '2021-02-01'
location = [11.756057739257812, 57.649809962218995, 12.10693359375, 57.751442372568924]

def get_all_files(*bands):
    # 执行检索
    bbox_search = Search(
        bbox=location, 
        datetime=f"{startDate}/{endDate}", 
        query={'eo:cloud_cover': {'lt': 50}},
        collections=[collection],
        url=url,
        sort={'field': 'eo:cloud_cover', 'direction': 'desc'},
    )
    items = bbox_search.items()

    downloads = {}
    # 外层循环内逐个新建独立字典,彻底避免引用覆盖
    for i, item in enumerate(items):
        data = {}
        data['Product ID'] = item.properties["sentinel:product_id"]
        data['Preview'] = item.asset("thumbnail")["href"]
        data['Date'] = item.properties["datetime"]
        
        # 新增异常捕获,避免单波段缺失中断整个流程
        for band in bands:
            try:
                data[band] = item.asset(band)["href"]
            except KeyError:
                data[band] = None
        
        downloads[i] = data
                            
    return downloads

display(JSON(get_all_files("B01", "B02", "B03")))

优化说明

  • 移除外层循环外的全局data定义,每个影像条目使用独立字典存储信息,彻底解决引用覆盖问题
  • 新增内层循环异常捕获,若单条目缺失指定波段,会写入None而非中断整个程序
  • 移除冗余的重复Search定义,避免重复发起检索请求
  • 用f-string拼接日期范围,代码可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 13:45:07