以下是使用Python实现按照连接时间和来源显示计数的示例代码:
from collections import defaultdict
from datetime import datetime
def count_by_time_and_source(data):
counts = defaultdict(int)
for item in data:
timestamp = item['timestamp']
source = item['source']
time = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
key = (time, source)
counts[key] += 1
return counts
# 示例数据
data = [
{'timestamp': '2022-01-01 09:00:00', 'source': 'A'},
{'timestamp': '2022-01-01 10:00:00', 'source': 'B'},
{'timestamp': '2022-01-01 09:00:00', 'source': 'A'},
{'timestamp': '2022-01-01 11:00:00', 'source': 'B'},
{'timestamp': '2022-01-01 10:00:00', 'source': 'A'},
]
result = count_by_time_and_source(data)
for key, value in result.items():
print(f"Time: {key[0]}, Source: {key[1]}, Count: {value}")
运行上述代码将输出以下结果:
Time: 2022-01-01 09:00:00, Source: A, Count: 2
Time: 2022-01-01 10:00:00, Source: B, Count: 1
Time: 2022-01-01 11:00:00, Source: A, Count: 1
Time: 2022-01-01 10:00:00, Source: A, Count: 1
该代码使用defaultdict
创建一个默认值为0的字典来存储计数结果。遍历输入数据列表,将时间戳和来源作为键,计数加1。最后遍历计数结果并输出。
下一篇:按照连续的行值创建组ID