Skip to main content
 首页 » 编程设计

python之如何使用每个值的范围从字典中获取所有可能的组合

2025年02月15日9zhenyulu

我将如何根据字典中的元组给定的范围从该字典创建所有可能的组合?

def createCombo(self): 
    usedAtoms = {'C':(0,100),'H':(0,200),'O':(0,4),'N':(0,4),'S':(0,4)} 
 
    MolecularFormula.combinations(self, usedAtoms) 
 
def combinations(self,dicts): 
 
    product = [x for x in apply(itertools.product, dicts.values())] 
    print [dict(zip(dicts.keys(), p)) for p in product] 

请您参考如下方法:

apply 现在在 python 中被弃用,使用 * 来扩展参数列表,例如

apply(itertools.product, dicts.values()) 

成为

itertools.product(*dicts.values()) 

对于您的问题,将 dicts.values() 替换为:

[range(*pair) for pair in dicts.values()]