遍历含空列表与字典的混合列表时,无法识别字典中的'sources'键问题排查
遍历含空列表与字典的混合列表时,无法识别字典中的'sources'键问题排查
嘿,我来帮你看看问题出在哪~
你的核心问题出在把plates转成DataFrame的操作上,咱们一步步拆解:
为什么原代码进不了if判断?
先看你的plates结构:它是一个列表,里面的元素要么是空列表[],要么是包含单个字典的列表(比如[{'plate ID': '193a', ...}])。当你把它转成plates_df = pd.DataFrame(plates)后,DataFrame的每一行其实是这些列表元素,而不是字典本身!
所以在遍历plates_df.iterrows()时,row并不是你想要的字典,row.keys()也不是字典的键,自然'sources' in row.keys()永远为False,代码根本进不去if块。
正确的处理方式:直接遍历原列表
不需要用DataFrame,直接遍历plates列表,针对每个元素做判断即可:
- 先跳过空列表
- 对非空的元素,取出里面的字典(因为每个非空元素是
[字典]的结构) - 再判断字典中是否存在
'sources'键
修正后的代码
import pandas as pd matched_plates = [] matches_sources_ra = [] matches_sources_dec =[] plates = [[], [], [{'plate ID': '193a', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441297986560, 99.28418829069784, 11.821604434173034], [3352465726807951744, 100.86164898224092, 12.756149587760696]]}], [{'plate ID': '194b', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441297986560, 99.28418829069784, 11.821604434173034], [3352465726807951744, 100.86164898224092, 12.756149587760696]]}], [], [], [], [], [], [], [], [], [], [], []] # 直接遍历plates列表 for plate_group in plates: # 跳过空列表 if not plate_group: continue # 取出列表中的字典(你的非空元素都是单字典列表) plate_dict = plate_group[0] # 判断字典中是否有sources键 if 'sources' in plate_dict: print(plate_dict["plate ID"]) matched_plates.append([plate_dict["plate ID"], len(plate_dict["sources"])]) # 提取第一个source的ra和dec matches_sources_ra.append(plate_dict["sources"][0][1]) matches_sources_dec.append(plate_dict["sources"][0][2]) # 可以打印看看结果 print("matched_plates:", matched_plates) print("matches_sources_ra:", matches_sources_ra)
额外小提示
如果你的plate_group(非空列表)里可能有多个字典,那可以再加一层遍历:
for plate_group in plates: if not plate_group: continue # 遍历列表中的每个字典 for plate_dict in plate_group: if 'sources' in plate_dict: # 后续操作和之前一样 print(plate_dict["plate ID"]) matched_plates.append([plate_dict["plate ID"], len(plate_dict["sources"])]) matches_sources_ra.append(plate_dict["sources"][0][1]) matches_sources_dec.append(plate_dict["sources"][0][2])
这样就可以覆盖更多可能的情况啦~
备注:内容来源于stack exchange,提问作者user123892
相关产品推荐
相关产品推荐

