首页 > 解决方案 > 全面返回python字典的所有可能组合

问题描述

我想返回 python 字典的所有可能的组合键。就我而言,它是一个两级层次结构字典。

我的第一次尝试似乎是一个类似伪代码的 for 循环序列。它有效,但它很丑陋,如果我有很多数据,它会变得非常痛苦。

我想用 dict-comprehension 方法做同样的任务。

这是我的尝试。使用这种技术,我很容易得到很多——太多了——for循环。

dic = {
    'Sex' : {'Man' : 0, 'Woman' : 1}, 
    'Age group' : {'0-14yrs' : 0, '15-25yrs' : 1, '26-35yrs' : 2}
}

for x in range(len(list(dic['Sex'].keys()))):
    for y in range(len(list(dic['Age group'].keys()))):
        sex = list(dic['Sex'].keys())[x]
        age = list(dic['Age group'].keys())[y]
        print(sex,age)


Man 0-14yrs
Man 15-25yrs
Man 26-35yrs
Woman 0-14yrs
Woman 15-25yrs
Woman 26-35yrs

标签: pythondictionarydictionary-comprehension

解决方案


我会用itertools.product.

for sex, age in itertools.product(dic['Sex'], dic['Age group']):
    print(sex, age)

product返回一个元组生成器,您可以根据自己的喜好进行操作。

对于一个任意dict的,您不一定事先知道键或它们的顺序,我会先用它的键标记每个值。

>>> for t in list(itertools.product(*[[(k, v) for v in dic[k] ] for k in dic])):
...   print(t)
...
(('Age group', '15-25yrs'), ('Sex', 'Woman'))
(('Age group', '15-25yrs'), ('Sex', 'Man'))
(('Age group', '0-14yrs'), ('Sex', 'Woman'))
(('Age group', '0-14yrs'), ('Sex', 'Man'))
(('Age group', '26-35yrs'), ('Sex', 'Woman'))
(('Age group', '26-35yrs'), ('Sex', 'Man'))

现在你至少知道了对应元组中每个值的“类型”;它不依赖于任何涉及原始的特定排序dict


推荐阅读