带有字典的列表的子集总和

Subset sum for a list with dict

给定 aList 为:

[
  {'name': 'Hailey', 'age': 20, 'id': 48479},
  {'name': 'John', 'age': 40, 'id': 18021},
  {'name': 'Asger', 'age': 18, 'id': 22281},
]

和给定的目标总和为 targetSum = 50

问题是用键 age 遍历 aList,然后从 aList 中删除元素 age 的值不能合并为相等(大约) targetSum。 可以组合等于(大约)targetSum 的元素应该可以通过它们在列表中的 id 检索。

或者,为了避免删除元素,问题只是找到给定元素的所有可能组合,这些元素的 age 属性总和(大约)为 targetSum

我有在列表中找到子集以求和的功能。然而,限制是它只需要一个数字列表,所以 [1, 2, 3, 4, ...] 而不是字典。

def subsetInListForSum(numbers, target):
    results = []
    for x in range(len(numbers)):
        results.extend(
            [   
                combo for combo in combinations(numbers ,x)  
                    if sum(combo) == target
            ]   
        )   

    print(results)

非常感谢任何帮助:)

由于您的函数适用于列表,因此只需从字典列表中提取年龄列表 aList,然后使用您的函数。

list_dicts = [{'name': 'Hailey', 'age': 20, 'id': 48479},
              {'name': 'John', 'age': 40, 'id': 18021},
              {'name': 'Asger', 'age': 18, 'id': 22281}]

list_ages = [d['age'] for d in list_dicts]

print(list_ages)
# Output
[20, 40, 18]

您的代码将按原样运行,因为 aList 仍然是一个列表。您只需要将 if 条件更改为

   if sum(val['age'] for val in combo) == target:

这样,您的 'results' 变量将包含 aList 中字典元素的所有组合,其年龄总和达到目标值。