根据箱子组合字典键

2024-10-04 11:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典

myDict = {1: 10, 1.1: 10, 2: 15, 2.1: 20}

但是它不是只有4个键值对,而是有数千个键值对,其中一些非常接近,比如我的例子中的键1和键1.1,有时甚至可以达到机器epsilon。你知道吗

有没有一个简单的程序,我可以把这些键放在一起,同时把它们对应的值加起来?在我的例子中,binwidth 1会变成

myBinnedDict = {1.05: 20, 2.05: 35}

在这里,我选择键作为前面键的平均值(甚至可以用对应键的值加权,但由于这是特定于应用程序的,所以在这里就不那么重要了)

谢谢你的帮助。你知道吗

注:我知道我最终来到这里是因为我可能没有很好地使用数据结构。你知道吗


Tags: 程序机器应用程序数据结构字典mydict例子键值
2条回答

我们可以使用一些numpy来利用一些数组操作。你知道吗

import numpy as np

myDict = {1: 10, 1.1: 10, 1.7: 6, 2: 15, 2.1: 20, 2.3: 50, 2.6: 1, 3: 1}

x = np.array([*myDict]) # just the keys from the dictionary

print(x)

array([1. , 1.1, 1.7, 2. , 2.1, 2.3, 2.6, 3. ])

clusters = x[x == x.astype(int)] # just the integers to get the bins

print(clusters)

array([1., 2., 3.])

digits = np.digitize(x, clusters) # bin the data based on the bins

print(digits)

array([1, 1, 1, 2, 2, 2, 2, 3])

res = dict()

for c in clusters:
    keys = x[digits == c] # grab all keys for this bin
    value = sum([myDict.get(k) for k in keys]) # sum values for these keys from the original dict
    res[keys.mean().round(2)] = value

print(res)

{1.27: 26, 2.25: 86, 3.0: 1}

您可以将itertools.groupby与一些单行理解结合使用:

from itertools import groupby
from statistics import mean

myDict = {1: 10, 1.1: 10, 2: 15, 2.1: 20}

{mean(keys): sum(vals) for keys, vals in (zip(*g) for _, g in groupby(sorted(myDict.items()), key=lambda x: round(x[0])))}

任何四舍五入到同一整数的数字都将被分组在一起。你知道吗

说明:

{
    mean(keys): sum(vals)
    for keys, vals in (
        zip(*g) for _, g in groupby(
            sorted(myDict.items()), 
            key=lambda x: round(x[0])
        )
    )
}

sorted(myDict.items())按键对字典排序(它按字典顺序排序,键排在第一位)。你知道吗

groupby(sorted(myDict.items()), key=lambda x: round(x[0])))}按舍入键的值对已排序的项进行分组。你知道吗

zip(*g) for _, g in groupby(...)表示这些组通过groupby吐出。groupby产生两个结果:我们不需要的“key”(舍入的数字)(用_表示)和格式为(key, val), (key, val), (key, val), etc.的“group”zip(*)将其转换成(key, key, key, ...), (val, val, val, ...),这就是我们需要的。你知道吗

最后,mean(keys): sum(vals) for keys, vals in (...)通过分别应用meansum来转换键和值。你知道吗

相关问题 更多 >