【问题标题】:Subset sum for a list with dict带有 dict 的列表的子集总和
【发布时间】:2016-06-04 05:32:26
【问题描述】:

给定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)

任何帮助将不胜感激:)

【问题讨论】:

  • len(numbers) 应该是 len(1, numbers+1)。否则,combinations(numbers ,x) 什么都不是。

标签: python list dictionary subset-sum


【解决方案1】:

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

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

这样,您的“结果”变量将由 aList 中字典元素的所有组合组成,其中年龄总和为目标值。

【讨论】:

    【解决方案2】:

    由于您的函数适用于列表,因此只需从字典列表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]
    

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多