python - 如何让所有排列从字典的每个值列表中选择一个项目?

标签 python list dictionary permutation

friend 们,基本上,我想听写:

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'}
]

怎么做?一百万!

最佳答案

您要查找的不是排列,而是 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)]

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

关于python - 如何让所有排列从字典的每个值列表中选择一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14048832/

相关文章:

swift - 追加到 [字符 : [object]] returns 0 key/value pair 的字典

python - python是如何实现以下数据格式转换的?

python - 获取任意文件类型的缩略图

python - 如何在 MacOSX 上用 pyinstaller 打包 tensorflow?

python - 测试 Django allauth

python - 高效地从 PyGithub 获取最新的 Commit URL

c# - 比较两个 List<String> 并仅保留唯一值的简单方法

php - 简单的 PHP 条件帮助 : if($Var1 = in list($List) and $Cond2) - Is this posslbe?

c# - 将锯齿状数组转换为列表

dictionary - 具有接收者函数回调的 Map 语法