gpt4 book ai didi

python - 全面返回python字典的所有可能组合

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:09 25 4
gpt4 key购买 nike

我想返回 python 字典的所有可能的组合键。在我的例子中,它是一个两级层次结构字典。

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

我想用字典理解方法完成同样的任务。

这是我的尝试。使用这种技术,我很容易得到很多——太多了——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

最佳答案

我会使用 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 的任何特定顺序。

关于python - 全面返回python字典的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54810773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com