以下是一个示例代码,实现了按照计数降序和时间进行分组和排序的功能:
from collections import defaultdict
from operator import itemgetter
from datetime import datetime
# 示例数据
data = [
{'id': 1, 'count': 3, 'time': '2021-05-01 10:00:00'},
{'id': 2, 'count': 2, 'time': '2021-05-01 11:00:00'},
{'id': 3, 'count': 5, 'time': '2021-05-01 12:00:00'},
{'id': 4, 'count': 3, 'time': '2021-05-02 10:00:00'},
{'id': 5, 'count': 4, 'time': '2021-05-02 11:00:00'},
{'id': 6, 'count': 2, 'time': '2021-05-02 12:00:00'},
]
# 按照计数进行分组
groups = defaultdict(list)
for item in data:
groups[item['count']].append(item)
# 对每个分组按照时间进行排序
sorted_groups = {count: sorted(group, key=itemgetter('time')) for count, group in groups.items()}
# 按照计数降序进行排序
result = sorted(sorted_groups.items(), key=lambda x: x[0], reverse=True)
# 输出结果
for count, group in result:
print(f"Count: {count}")
for item in group:
print(f"ID: {item['id']}, Time: {item['time']}")
print()
这段代码首先使用defaultdict(list)
创建一个字典,用于按照计数进行分组。然后遍历数据,将每个item添加到对应计数的分组中。
接下来,对每个分组中的数据按照时间进行排序,使用sorted()
函数和itemgetter()
函数实现按照时间排序。
最后,使用sorted()
函数对分组进行按照计数降序排序,通过指定key=lambda x: x[0]
进行按照字典键(计数)进行排序。
最终,按照计数降序输出每个分组的数据。
上一篇:按照计数分组不能提供正确的结果
下一篇:按照计数值在对象数组中重复的对象