首页 > 解决方案 > 如何在 Python 中对几个字典进行线性组合?

问题描述

这里有一些代码可以对两个字典进行线性组合:

def linearcombination(a1,d1,a2,d2):
    return {k:a1*d1.get(k,0)+a2*d2.get(k,0) for k in {**d1,**d2}.keys()}


choosy1={"a":1,"b":2,"c":3}
choosy2={"a":1,"d":1}
choosy=linearcombination(1,choosy1,10,choosy2)

挑剔的是:

{'a': 11, 'c': 3, 'd': 10, 'b': 2}

我怎样才能概括它以允许任意数量的字典的线性组合?

标签: python

解决方案


sum在一组键上使用 dict 理解的解决方案:

from itertools import chain

def linear_combination_of_dicts(dicts, weights):
    return {
        k: sum( w * d.get(k, 0) for d, w in zip(dicts, weights) )
        for k in set(chain.from_iterable(dicts))
    }

例子:

>>> dicts = [{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'd': 1}]
>>> weights = [1, 10]
>>> linear_combination_of_dicts(dicts, weights)
{'c': 3, 'd': 10, 'a': 11, 'b': 2}

推荐阅读