- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在 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/
我是一名优秀的程序员,十分优秀!