python - 如何在 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}
我怎样才能概括它以允许任意数量的字典的线性组合?
解决方案
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}
推荐阅读
- sql - 如何查找不同的列,计算不同的列,将它们与与其他列同名的其他列合并
- c# - 从 C# 中的点列表中删除异常值
- node.js - Firebase 函数 + Firestore:ignoreUndefinedProperties 在事务中不起作用
- c++ - 如何在 C++ 中从具有不同概率的数组中随机选择元素
- haskell - haskell 函数/模式运算符
- mysql - 尝试对 sql 进行除法运算时出现 var char 错误
- swiftui - 为什么 watchOS 选择器总是显示“ScrollView contentOffset binding has been read”警告?
- c# - 无法使用 Xunit 测试端点 - StatusCode: 400, ReasonPhrase: 'Bad Request'
- java - 天气应用程序未显示回收站视图(在卡片视图中)。尝试了 Stack Overflow 的解决方案。没有任何工作
- time - 指定周期性时间间隔(例如:办公室的营业时间)