列表字典的笛卡尔积 [英] Cartesian product of a dictionary of lists

查看:89
本文介绍了列表字典的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些代码来测试一堆输入参数的笛卡尔积。

I'm trying to write some code to test out the Cartesian product of a bunch of input parameters.

我查看了 itertools ,但是它的 product 函数并不是我想要的。是否有一种简单明了的简单方法来制作一个字典,在每个值中包含任意数量的键任意数量的键,然后生成具有下一个排列的字典?

I've looked at itertools, but its product function is not exactly what I want. Is there a simple obvious way to take a dictionary with an arbitrary number of keys and an arbitrary number of elements in each value, and then yield a dictionary with the next permutation?

输入:

options = {"number": [1,2,3], "color": ["orange","blue"] }
print list( my_product(options) )

示例输出:

[ {"number": 1, "color": "orange"},
  {"number": 1, "color": "blue"},
  {"number": 2, "color": "orange"},
  {"number": 2, "color": "blue"},
  {"number": 3, "color": "orange"},
  {"number": 3, "color": "blue"}
]


推荐答案

好,谢谢@dfan告诉我找错地方了。我现在知道了:

Ok, thanks @dfan for telling me I was looking in the wrong place. I've got it now:

from itertools import product
def my_product(inp):
    return (dict(zip(inp.keys(), values)) for values in product(*inp.values())

编辑:经过多年的Python经验,我认为更好的解决方案是接受 kwargs 而不是输入字典;调用样式与原始 itertools.product 的样式更相似。我还认为编写生成器函数(而不是返回生成器表达式的函数)可以使代码更清晰。因此:

EDIT: after years more Python experience, I think a better solution is to accept kwargs rather than a dictionary of inputs; the call style is more analogous to that of the original itertools.product. Also I think writing a generator function, rather than a function that returns a generator expression, makes the code clearer. So:

def product_dict(**kwargs):
    keys = kwargs.keys()
    vals = kwargs.values()
    for instance in itertools.product(*vals):
        yield dict(zip(keys, instance))

,如果您需要传递字典,请输入 list(product_dict(** mydict))。使用 kwargs 进行更改,而不是使用任意输入cla ss是它可以防止对键/值进行排序,至少直到Python 3.6为止。

and if you need to pass in a dict, list(product_dict(**mydict)). The one notable change using kwargs rather than an arbitrary input class is that it prevents the keys/values from being ordered, at least until Python 3.6.

这篇关于列表字典的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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