python - 全面返回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
解决方案
我会用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
。
推荐阅读
- css - 更改数据表过滤器下拉框的颜色
- python - 在 matplotlib 中创建带有自由 y 轴的箱形图的子图
- linux - aarch64 内核映像中的 text_offset 是什么,我如何知道内核入口点在哪里?
- arrays - 如何手动获取已使用过滤器将数据格式化为日期的 JSON 数组中的第一个元素项?
- javascript - Instagram 浏览器不会激活手机的位置
- java - log4j LogEventPatternConverter - 如何仅记录格式化的 Throwable 堆栈跟踪?
- amazon-web-services - AWS Amplify Fullstack CI/CD 中断 API(cors 问题)
- amazon-web-services - ECS_CONTAINER_METADATA_URI_v4 不可用
- python - 加载的武器不会在循环内随机重新加载
- python - PyQT:无法正确填充 QTTreeView 列