
本文讲解如何高效遍历由空列表和含 sources 键的字典组成的多层嵌套列表(如 plates),精准提取 plate id、source 数量及首个 source 的 ra/dec 坐标,避免误用 pandas 导致逻辑失效。
本文讲解如何高效遍历由空列表和含 sources 键的字典组成的多层嵌套列表(如 plates),精准提取 plate id、source 数量及首个 source 的 ra/dec 坐标,避免误用 pandas 导致逻辑失效。
原始数据 plates 是一个包含 12 个元素的顶层列表,其中多数为空列表 [],仅第 2 和第 3 个索引位置(即 plates[2] 和 plates[3])存储了非空列表,而这些列表内部又包含单个字典——该字典拥有 'sources' 键。关键问题在于:Pandas DataFrame 无法直接对嵌套结构中的字典键做成员判断。当你执行 plates_df.iterrows() 时,每一行 row 实际是 pd.Series 对象,其 .keys() 返回的是列索引(此处为 RangeIndex(0, 12)),而非字典的键;因此 'sources' in row.keys() 永远为 False,导致循环体从未执行。
正确的做法是放弃 Pandas,采用原生 Python 多层遍历:先遍历顶层 plates 列表,再遍历每个子列表中的元素(跳过空列表),最后对每个字典检查 'sources' 键是否存在。
以下是简洁、健壮且可读性强的实现:
matched_plates = []
matches_sources_ra = []
matches_sources_dec = []
for sublist in plates: # 遍历顶层列表:plates[0], plates[1], ...
for item in sublist: # 遍历子列表内每个元素(通常是字典,也可能是其他类型)
if isinstance(item, dict) and 'sources' in item:
plate_id = item['plate ID']
print(plate_id)
matched_plates.append([plate_id, len(item['sources'])])
# 安全提取首个 source 的 RA (索引1) 和 Dec (索引2),假设 sources 非空
if item['sources']:
ra, dec = item['sources'][0][1], item['sources'][0][2]
matches_sources_ra.append(ra)
matches_sources_dec.append(dec)✅ 输出结果:
# matched_plates → [['193a', 2], ['194b', 2]] # matches_sources_ra → [99.28418829069784, 99.28418829069784] # matches_sources_dec → [11.821604434173034, 11.821604434173034]
⚠️ 注意事项:
- 不要滥用 Pandas:本场景无行列对齐、统计聚合或向量化计算需求,引入 DataFrame 只会增加内存开销与逻辑复杂度;
-
类型防护很重要:添加
isinstance(item, dict)判断,防止子列表中意外混入非字典对象(如字符串、数字)导致KeyError或AttributeError; -
空 sources 防御:在访问
item['sources'][0]前应检查if item['sources']:,避免索引越界; - 若需提取所有 sources 而非仅首个,可改用嵌套循环:
for src in item['sources']: matches_sources_ra.append(src[1])。
这种纯 Python 的递进式遍历清晰表达了数据的真实结构(list of lists of dicts),语义直观、性能优异,是处理此类嵌套异构数据的标准实践。

















