如何编写python方法来计算列表字典的所有组合? [英] How can I write a python method to compute all combinations of a dict of lists?

查看:187
本文介绍了如何编写python方法来计算列表字典的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意的python字典 x ,这样每个键的值本身就是一个列表。下面是一个示例:

I have an arbitrary python dictionary x such that the values of each key is itself a list. Here is an example:

x = {"first_name": ["Mahmoud", "Pei-chi"], "second_name": ["Abadi", "Yao"]}

给出 x 我想写一个方法来计算字典列表,这样每个字典都具有与x相同的键,但是值分别是单个列表元素的组合。因此,在这种情况下,结果应为:

Given x I would like write a method that computes a list of dictionaries such that each dictionary has the same keys as x but the values are each combination of individual list element. So in this case, the result should be:

[{"first_name": "Mahmoud", "second_name": "Abadi"}, 
 {"first_name": "Mahmoud", "second_name": "Yao"}, 
 {"first_name": "Pei-chi", "second_name": "Abadi"}, 
 {"first_name": "Pei-chi", "second_name": "Yao"}]

我该怎么办?字典 x 可以具有任意数量的具有任意名称的键。

How can I do it? The dictionary x may have any arbitrary number of keys with arbitrary names.

推荐答案

您可以发布以下列表信息。

You can issue the following list comprehension.

result = [dict(zip(x.keys(), t)) for t in product(*x.values())]

这篇关于如何编写python方法来计算列表字典的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆