【问题标题】:Can i get a range of values from dictionary?我可以从字典中获取一系列值吗?
【发布时间】:2023-01-24 19:39:36
【问题描述】:

我想从我的字典中获取一系列值,但不是所有值

temperature = {
    "01.01.2023": "10",
    "02.01.2023": "15",
    "03.01.2023": "20",
    "04.01.2023": "25",
    "05.01.2023": "30",
}

例如,用户想要获取从“03.01.2023”到“05.01.2023”的值,但不想从此字典中获取任何其他值。 我想计算用户指定范围之间的平均温度,但我在谷歌上找不到任何东西......

在互联网上找不到任何东西,尝试使用 range() 但显然没有用

【问题讨论】:

  • 你到底想要什么?两者之间或只是 min/max 之间的所有值的列表?编辑:我认为,这是因为类型是 str。 tange 只需要 int。 'range(int(temperature[date_min], int(temperature[date_max])' 应该有效。
  • “03.01.2023”和“05.01.2023”之间的值列表
  • 键是否总是按照您在帖子中的排序,从 01.01 到 05.01?
  • 快速谷歌搜索结果中有很多关于过滤字典的结果
  • 编程不是“在谷歌上找到任何东西”。你必须自己编码。

标签: python dictionary


【解决方案1】:

这是查找两个日期之间的平均温度的代码:

from datetime import datetime, timedelta

temperature = {
    "01.01.2023": "10",
    "02.01.2023": "15",
    "03.01.2023": "20",
    "04.01.2023": "25",
    "05.01.2023": "30",
}

def avg_temp(start_date, end_date):
    start_date = datetime.strptime(start_date, r"%d.%m.%Y")  # convert to datetime object
    end_date = datetime.strptime(end_date, r"%d.%m.%Y")  # convert to datetime object
    days = (end_date - start_date).days + 1  # get number of days between two dates
    
    # Get temperatures for each day
    temps = [temperature[(start_date + timedelta(days=i)).strftime(r"%d.%m.%Y")] for i in range(days)]
    
    return sum(temps) / days

print(avg_temp("01.01.2023", "05.01.2023"))  # 20.0
print(avg_temp("03.01.2023", "05.01.2023"))  # 25.0
  • 它需要您要检查平均温度的开始日期和结束日期。
  • 将它们转换为 datetime 对象。
  • 计算它们之间的天数。
  • temperature 字典中收集日期的温度
  • 计算平均温度。

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2011-09-29
    相关资源
    最近更新 更多