python - 更新值并保留python字典上的键
问题描述
我有一个停车位应用程序,我想在其中计算一周中的可用天数以及每天的总可用小时数。
我有不同的城市,有不同的时移,有些是全职的(例如 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}]
键是星期几,值是该班次的小时数。有没有办法对同一个键的值求和?
解决方案
看看计数器。https://docs.python.org/3/library/collections.html#collections.Counter 它可用于对具有相同键的单独字典的值求和。IE
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}
推荐阅读
- java - 我们可以在 App 模块中使用库模块的资源吗?
- android - 使用 Mp 图表为组条中的每个单独条设置名称
- spacy - 在 spacy 实体链接中显示来自 kb id 的实体描述
- r - 如何在 Mac 上增加 R 的内存限制?
- python - 在递归下传递Python函数内部变量的值
- python - TypeError:传递 PeriodDtype 数据无效。改用`data.to_timestamp()`
- scala - 如何使用主类选择对话框?
- google-apps-script - 从不是由 Google Apps 脚本创建的文件中获取元数据
- c++ - 如何从派生类的构造函数中正确访问这个基类变量?
- android - Android camera2 ImageReader导致冻结