gpt4 book ai didi

python - 如何对 key :value pairs in a python dictionary based on certain range or interval? 进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:25 25 4
gpt4 key购买 nike

我在 python 中有一个字典 dict={14:1, 15:2, 16:4, 11:5, 20:1,22:5,25:2...}

如何在任何数据结构(字典或其他东西)中获得最终结果,如下所示:

Final= [10-15:8, 16-20:5, 21-25:7....] 或者至少可以对落在特定范围内的键的值求和比方说 10-15、15-20 等等。

最终目标是将数据容器化以构建直方图或条形图。

最佳答案

from itertools import groupby

my_dict = {14:1, 15:2, 16:4, 11:5, 20:1, 22:5, 25:2}
key_fn, result = lambda (x, _): x / 5 + 1 if x % 5 else x / 5, {}

for item, grp in groupby(sorted(my_dict.items(), key = key_fn), key_fn):
result[((item - 1) * 5 + 1, item * 5)] = sum(count for _, count in grp)

print result

输出

{(11, 15): 8, (21, 25): 7, (16, 20): 5}

关于python - 如何对 key :value pairs in a python dictionary based on certain range or interval? 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21131601/

25 4 0
文章推荐: javascript - 如何让 保持固定高度? Bootstrap 4