【问题标题】:How do I get all the permutations selecting one item from each value list in a dictionary?如何从字典中的每个值列表中选择一个项目的所有排列?
【发布时间】:2012-12-27 02:55:52
【问题描述】:

朋友们,基本上,我想听听听写:

fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}

并通过在不同键的所有值之间进行所有可能的排列来获得以下字典列表:

output_list = 
[
{'oranges':'big','apples':'green'},
{'oranges':'big','apples':'yellow'},
{'oranges':'big','apples':'red'},
{'oranges':'small','apples':'green'},
{'oranges':'small','apples':'yellow'},
{'oranges':'small','apples':'red'}
]

怎么做?谢谢一百万!

【问题讨论】:

    标签: python list dictionary permutation


    【解决方案1】:

    您要查找的不是排列,而是Cartesian product。把它想象成一个嵌套循环。

    from itertools import product
    
    fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}    
    
    keys, values = zip(*fruit_dict.items())
    print [dict(zip(keys, value_list)) for value_list in product(*values)]
    

    然后,您只需使用现有密钥和产品中的每个项目创建一个新字典。

    【讨论】:

    • 非常感谢,agf!根据需要工作。
    【解决方案2】:

    使用itertools.product():

    In [94]: dic = {'oranges':['big','small'],'apples':['green','yellow','red']}
    
    In [95]: sort_values=[x[1] for x in sorted(dic.items())]  #sorted values based on keys
    
    In [96]: [dict(zip(sorted(dic.keys()),x)) for x in product(*sort_values)]
    Out[96]: 
    [{'apples': 'green', 'oranges': 'big'},
     {'apples': 'green', 'oranges': 'small'},
     {'apples': 'yellow', 'oranges': 'big'},
     {'apples': 'yellow', 'oranges': 'small'},
     {'apples': 'red', 'oranges': 'big'},
     {'apples': 'red', 'oranges': 'small'}]
    

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多