python - 我想找到一天中办公室最高峰的时间

标签 python python-3.x list

我有一个列表a = [(1,3),(3,7),(1,10),(3,5),......]所以在。即(进入时间,退出时间)。

其中每个元组中的第一个元素是员工的上类时间,第二个元素是退出时间。需要找到一天中办公室里人数最多的时间。

例如输出:

{1'00: 10, 2'00: 20, 3'00: 15}

因此最终输出应为 2'00,计数为 20。

最佳答案

使用带有 flatten 和 range 的列表理解,然后使用 collections.Counter最后提取最大值:

a = [(1, 3), (3, 7), (1, 10), (3, 5)]

from collections import Counter

d = Counter([f'{y}:00' for s, e in a for y in range(s, e + 1)])
print(d)
Counter({'3:00': 4, '4:00': 3, '5:00': 3, '1:00': 2, '2:00': 2,
     '6:00': 2, '7:00': 2, '8:00': 1, '9:00': 1, '10:00': 1})

maximum = max(d, key=d.get)
print(maximum, d[maximum])

3:00 4

如果元组的最后一个值不是计数:

d = Counter([f'{y}:00' for s, e in a for y in range(s, e)])
print (d)
Counter({'3:00': 3, '4:00': 3, '1:00': 2, '2:00': 2,
         '5:00': 2, '6:00': 2, '7:00': 1, '8:00': 1, '9:00': 1})

maximum = max(d, key=d.get)
print(maximum, d[maximum])
3:00 3

关于python - 我想找到一天中办公室最高峰的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484008/

相关文章:

python - 定义异常时不必要的传递

python-3.x - AES-CTR 和 AES-GCM 生成的不同密文

python - Groupby & Sum 从某个特定值的出现到另一个特定值或相同值的出现

python - 将项目 append 到列表理解中的列表

c# - 我应该如何从自定义对象的 List<T> 中提取不同值的集合?

python - 如何使用正则表达式获取在字符串中重复多次的模式

python - PyCharm 错误 - 名称 'chicks' 可以未定义

python - Linux 屏幕上的 Flash 字符

python - 定义类覆盖的问题 (__not__)

python - 遍历 python 列表列表并根据条件删除列表