我有一本字典
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}
在这里,我选择键作为前面键的平均值(甚至可以用对应键的值加权,但由于这是特定于应用程序的,所以在这里就不那么重要了)
谢谢你的帮助。你知道吗
注:我知道我最终来到这里是因为我可能没有很好地使用数据结构。你知道吗
我们可以使用一些
numpy
来利用一些数组操作。你知道吗您可以将
itertools.groupby
与一些单行理解结合使用:任何四舍五入到同一整数的数字都将被分组在一起。你知道吗
说明:
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 (...)
通过分别应用mean
和sum
来转换键和值。你知道吗相关问题 更多 >
编程相关推荐