Jupyter Notebook中使用sorted()按时长属性排序报错求助
问题分析与解决
你的代码报错核心原因是:sorted()函数返回的是排序后的列表,而非单个字典。sightings_us里的每个元素应该是包含datetime和duration (seconds)的字典,排序后fballsorted是这些字典组成的列表,不能直接用字典键(比如["datetime"])去索引整个列表,这会触发类型错误。
修正代码示例
1. 打印所有排序后的条目
fballsorted = sorted(sightings_us, key=lambda x: x["duration (seconds)"], reverse=True) # 遍历列表里的每个字典,打印对应字段 for item in fballsorted: print(item["datetime"], item["duration (seconds)"])
2. 打印排序后的前N条(比如前5条)
fballsorted = sorted(sightings_us, key=lambda x: x["duration (seconds)"], reverse=True) # 取前5条遍历打印 for item in fballsorted[:5]: print(item["datetime"], item["duration (seconds)"])
3. 打印单个条目(比如第一条)
如果你只想看排序后的第一条数据,可以直接用列表索引:
fballsorted = sorted(sightings_us, key=lambda x: x["duration (seconds)"], reverse=True) print(fballsorted[0]["datetime"], fballsorted[0]["duration (seconds)"])
内容的提问来源于stack exchange,提问作者azrai
相关产品推荐
相关产品推荐

