简体   繁体   English

如何使用Python中的字典找到值总和等于或大于k的键的可能组合?

[英]How to find possible combination of keys having sum of values equal or greater than k using dictionary in Python?

d1= {"Noodles":20, "Burger":10, "Sandwitch":20}
d2= {"Pepsi": 20, "Coke": 25, "Soup": 15, "Sprite":10}
dic = {**d1, **d2}
keys = dic.keys()

import itertools
all_comb = list(itertools.combinations(keys, 4))

for val in all_comb:
    lt = list(val)
    sum = dic[lt[0]] + dic[lt[1]] + dic[lt[2]] + dic[lt[3]]
    if sum < 70:
        all_comb = all_comb.remove(val)
    else:
        continue
print(all_comb)

This code is displaying all the combination of keys, I want to display only the combinations having a sum of 70 or greater.此代码显示所有键组合,我只想显示总和为 70 或更大的组合。

The main problem is that you remove items from the list while iterating on it.主要问题是您在迭代列表时从列表中删除了项目。 As a general rule, don't do that, you're going to miss items.作为一般规则,不要这样做,你会错过项目。 You should rather build a new list.您应该构建一个新列表。

In your case, it is better to only keep the valid combinations while you iterate on the output of itertools.combinations .在您的情况下,最好在迭代itertools.combinations的输出时仅保留有效组合。 You should not use list(itertools.combinations(...)) : this forces all possible combinations to be calculated and stored immediately, which you don't need, and is inefficient.您不应该使用list(itertools.combinations(...)) :这会强制立即计算和存储所有可能的组合,这是您不需要的,而且效率低下。 The functions in itertools are, as the name of the module suggests, iterators.正如模块名称所暗示的那样, itertools中的函数是迭代器。 They generate their output values lazily, one by one.他们一个接一个地懒惰地生成输出值。

Just do:做就是了:

for combination in itertools.combinations(...):
    # check the combination and store it if valid

As a side note, avoid using the names of Python builtin functions (like sum ) as variable names, as this shadows the original functions.作为旁注,避免使用 Python 内置函数的名称(如sum )作为变量名称,因为这会影响原始函数。

So, your code could be:所以,你的代码可能是:

import itertools


d1= {"Noodles":20, "Burger":10, "Sandwitch":20}
d2= {"Pepsi": 20, "Coke": 25, "Soup": 15, "Sprite":10}
dic = {**d1, **d2}
keys = dic.keys()

valid_combinations = []
for comb in itertools.combinations(keys, 4):
    total = sum(dic[key] for key in comb)
    if total >= 70:
        valid_combinations.append(comb)
        
print(valid_combinations)
# [('Noodles', 'Burger', 'Sandwitch', 'Pepsi'), 
#  ('Noodles', 'Burger', 'Sandwitch', 'Coke'), 
#  ('Noodles', 'Burger', 'Pepsi', 'Coke'),
#  ('Noodles', 'Burger', 'Coke', 'Soup'),
 #  .... ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 得到一个字典键的计数,其值大于python中的某个整数 - get a count of dictionary keys with values greater than some integer in python 如何在字典中的给定键处找到值的总和? - How to find the sum of values at given keys in a dictionary? Python-总和大于或等于值的数字组合 - Python - Combination of Numbers Summing to Greater than or Equal to a Value 将相等值的变量用作字典键会导致覆盖值(Python) - Using variables of equal value as dictionary keys results in overwritten values (Python) Python:值的总和大于最后一个值 - Python: sum of values greater than last value 如何使 python 大于/小于或等于? - How to make a greater/less than or equal to on python? Python通过大于或等于每个子组中位数的列值找出数据帧中的记录 - Python find out records in dataframe by column values greater than or equal to their median in each subgroup 如何对具有字符串作为键和 integer 作为 Python 中的值的字典进行排序 - How to sort a dictionary having string as keys and integer as values in Python 如何将具有键作为元组的python字典中的值相加 - how to sum values from a python dictionary having key as tuple Python Dictionary使用Lists作为值,查找具有相同值的其他键 - Python Dictionary using Lists as Values, find other Keys with same values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM