任意个dict笛卡尔积的和元组

2024-09-30 16:31:05 发布

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

我想根据多个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]}


Tags: keyinforifnotprodkeysdict
1条回答
网友
1楼 · 发布于 2024-09-30 16:31:05

您可以这样做,首先按键重新组织数据:

from collections import defaultdict
from itertools import product


def doProdSum(list_of_dicts):
    # We reorganize the data by key
    lists_by_key = defaultdict(list)
    for d in list_of_dicts:
        for k, v in d.items():
            lists_by_key[k].append(v)

    # list_by_key looks like {'a': [[0, 1, 2], [1, 1, 1]], 'b': [[10], [1, 2, 3, 4, 5]],'c': [[1, 2, 3, 4]]}

    # Then we generate the output
    out = {}
    for key, lists in lists_by_key.items():
        out[key] = [sum(prod) for prod in product(*lists)]

    return out

示例输出:

list_of_dicts = [{"a":[0,1,2],"b":[10],"c":[1,2,3,4]}, {"a":[1,1,1],"b":[1,2,3,4,5]}]
doProdSum(list_of_dicts)

# {'a': [1, 1, 1, 2, 2, 2, 3, 3, 3],
#  'b': [11, 12, 13, 14, 15],
#  'c': [1, 2, 3, 4]}

相关问题 更多 >