【问题标题】:Update value and keep the key on python dictionary更新值并保留python字典上的键
【发布时间】:2021-07-27 14:31:29
【问题描述】:

我有一个停车位应用程序,我想在其中计算一周中的可用天数以及每天的总可用小时数。

我在不同的城市有不同的时移,有些是全职(例如 7:00-20:00),有些是分开的时间(例如 7:00-14:00 和 16:00-20:00) .

这是我尝试过的循环:

def get_available_hours(self):
    _dict = []
    time = 0
    query_set = TimeTableCity.objects.filter(city_id=self._city_id)
    for i in query_set:
        initial_hour_datetime = datetime.strptime(i.initial_hour, '%H:%M')
        end_hour_datetime = datetime.strptime(i.end_hour, '%H:%M')
        time = end_hour_datetime - initial_hour_datetime
        _dict.append({i.day_table.id: time.seconds / 3600})
        time = 0
    return _dict

最后返回的dict如下:

[{4: 5.0}, {4: 4.0}, {5: 5.0}, {5: 4.0}, {1: 5.0}, {1: 4.0}, {2: 5.0}, {2: 4.0}, {3: 5.0}, {3: 4.0}]

键是星期几,值是该班次的小时数。 有没有办法对同一个键的值求和?

【问题讨论】:

  • 请分享您的模型:TimeTableCity 和相关模型。
  • 完全有必要吗?它按预期工作,我只想用相同的键 @WillemVanOnsem 对值求和
  • @peplover 看起来您使用CharField 而不是TimeField 来存储时间?另外,您执行的计算可以很容易地在数据库端完成。正如 Willem Van Onsem 所说,您应该添加您的模型,这样人们就可以提出更好的解决方案。
  • @peplover:最好在 database 级别进行这些聚合,因为这样更快,并且需要更少的带宽。
  • 由于我无法修改数据库,我只需要按照我显示的方式进行操作即可。对不起,如果我没有指定

标签: python django dictionary


【解决方案1】:

你可以使用get函数。

def get_available_hours(self):
    _dict = {}
    time = 0
    query_set = TimeTableCity.objects.filter(city_id=self._city_id)
    for i in query_set:
        initial_hour_datetime = datetime.strptime(i.initial_hour, '%H:%M')
        end_hour_datetime = datetime.strptime(i.end_hour, '%H:%M')
        time = end_hour_datetime - initial_hour_datetime

        _dict[i.day_table.id] = _dict.get(i.day_table.id, 0) + (time.seconds / 3600)
        
        time = 0
    return _dict

【讨论】:

【解决方案2】:

看看计数器。 https://docs.python.org/3/library/collections.html#collections.Counter 它可用于对具有相同键的单独 dicts 的值求和。 浏览器

from collections import Counter

a = {'a': 5, 'b': 7}
b = {'a': 3, 'b': 2, 'c': 5}
dict(Counter(a)+Counter(b))

--

Out[7]: {'a': 8, 'b': 9, 'c': 5}

【讨论】:

    【解决方案3】:

    此方法无需导入即可工作,但可能有人会评论一个更干净的方法,但我认为它非常易读

    d = [{4: 5.0}, {4: 4.0}, {5: 5.0}, {5: 4.0}, {1: 5.0}, {1: 4.0}, {2: 5.0}, {2: 4.0}, {3: 5.0}, {3: 4.0}]
    summed = {}
    for item in d:
        day_of_week = list(item.keys())[0]
        if day_of_week not in summed:
            summed[day_of_week] = item[day_of_week]
        else:
            summed[day_of_week] += item[day_of_week]
    

    结果:

    Out[12]: {4: 9.0, 5: 9.0, 1: 9.0, 2: 9.0, 3: 9.0}
    

    【讨论】:

    • @peplover 不用担心 :)
    猜你喜欢
    • 2023-03-30
    • 2014-09-04
    • 1970-01-01
    • 2023-03-28
    • 2023-02-03
    • 1970-01-01
    • 2016-07-10
    • 2019-04-01
    • 1970-01-01
    相关资源
    最近更新 更多