Skip to main content
 首页 » 编程设计

Python之使用 min() 在 JSON 对象中查找最小值

2025年05月04日15emanlee

所以我有一个 geojson 对象:

"features" : [{"properties": {"rank": 10}},{"properties": {"rank": 2}}] 

等等。我想找到最低等级并使用 min方法。所以我尝试了这样的事情:

features = geojson["features"] 
min(features["properties"]["rank"]) 

然后:

features = geojosn["features"]["properties"]["rank"] 
min(features) 

并且在两者上都得到了这个:

TypeError: List indices must be integers of slices, not str

我做错了什么?任何帮助将不胜感激,谢谢!!!

请您参考如下方法:

我假设您有一个包含属性的功能列表(因为@idjaw 指出您的数据结构无效)。然后 geojson['features'] 是一个列表,你没有索引列表。您可以使用生成器执行此操作:

min(feature["properties"]["rank"] for feature in geojson['features']) 

或者,如果您想要恢复整个功能,则可以使用键:

min(geojson['features'], key=lambda feature: feature["properties"]["rank"])