You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从含嵌套列表的Python字典中提取最大最小体重及单键近30天最低值

问题原因

你之前的代码存在两个核心问题:

  • 直接遍历字典默认取的是字典的键(比如Pig、Cow这类字符串),没有深入到嵌套列表里的体重字段取值
  • 原字典里存储的体重是字符串格式,无法直接进行数值大小比较,日期也是字符串格式,无法直接计算时间差

可行实现代码

from datetime import datetime, timedelta

# 示例字典,修正了原示例中缺失列表闭合括号的语法问题
dic = {
    'Pig': [['21-08-01', '67.12'], ['21-08-02', '65.32'], ['21-08-05', '55.56'], ['21-08-06', '59.49'], ['21-08-07', '58.63']],
    'Cow': [['21-08-01', '140.23'], ['21-08-02', '135.12'], ['21-08-05', '131.35'], ['21-08-06', '182.42'], ['21-08-07', '145.30']],
    'Horse': [['21-08-01', '210.12'], ['21-09-01', '205.34']]
}

# ------------------------------
# 需求1:提取全局最大、最小体重
# ------------------------------
all_weights = []
for animal_records in dic.values():
    for record in animal_records:
        # 字符串体重转浮点数后存入统一列表
        all_weights.append(float(record[1]))
global_max = max(all_weights)
global_min = min(all_weights)
print(f"全局最大体重:{global_max},全局最小体重:{global_min}")

# ------------------------------
# 需求2:每个分类下近30天的最低体重
# ------------------------------
# 可根据业务需求修改基准日期,默认取当前系统日期
base_date = datetime.today()
# 若测试历史数据可手动指定基准日期,例:base_date = datetime.strptime('21-09-07', '%y-%m-%d')
min_weight_per_animal = {}
for animal, records in dic.items():
    recent_records = []
    for record in records:
        record_date = datetime.strptime(record[0], '%y-%m-%d')
        if (base_date - record_date) <= timedelta(days=30):
            recent_records.append(float(record[1]))
    # 无符合条件的记录时返回None,可自定义默认值
    min_weight_per_animal[animal] = min(recent_records) if recent_records else None

print("各分类近30天最低体重:", min_weight_per_animal)

代码说明

  • 体重统一转为float类型后再做大小比较,避免字符串排序出现的逻辑错误
  • 日期通过datetime.strptime转为时间对象后,用timedelta计算时间差判断是否属于近30天范围
  • 无符合要求的近30天记录时,对应分类返回值为None,可根据实际需求修改默认返回值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:45:07