我想根据多个dict的键进行笛卡尔积,然后对生成的元组求和,并将其作为dict返回。应该忽略一个dict中不存在的键(这个约束是理想的,但不是必需的;i、 e.如果需要,您可以假设所有DICT中都存在所有密钥)。下面是我试图实现的基本目标(以两个dict为例)。有没有一种更简单的方法来实现这一点,并且使用N个dicts
def doProdSum(inp1, inp2):
prod = defaultdict(lambda: 0)
for key in set(list(inp1.keys())+list(inp2.keys())):
if key not in prod:
prod[key] = []
if key not in inp1 or key not in inp2:
prod[key] = inp1[key] if key in inp1 else inp2[key]
continue
for values in itertools.product(inp1[key], inp2[key]):
prod[key].append(values[0] + values[1])
return prod
x = doProdSum({"a":[0,1,2],"b":[10],"c":[1,2,3,4]}, {"a":[1,1,1],"b":[1,2,3,4,5]})
print(x)
产出(如预期):
{'c': [1, 2, 3, 4], 'b': [11, 12, 13, 14, 15], 'a': [1, 1, 1, 2, 2, 2, 3, 3, 3]}
您可以这样做,首先按键重新组织数据:
示例输出:
相关问题 更多 >
编程相关推荐