如何将itertools.product应用于列表列表的元素? [英] How to apply itertools.product to elements of a list of lists?

查看:127
本文介绍了如何将itertools.product应用于列表列表的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组列表,我想获取数组中元素的笛卡尔积.

I have a list of arrays and I would like to get the cartesian product of the elements in the arrays.

我将使用一个示例来使其更加具体...

I will use an example to make this more concrete...

itertools.product似乎可以解决问题,但我只保留了一些细节.

itertools.product seems to do the trick but I am stuck in a little detail.

arrays = [(-1,+1), (-2,+2), (-3,+3)];

如果我愿意

cp = list(itertools.product(arrays));

我知道

cp = cp0 = [((-1, 1),), ((-2, 2),), ((-3, 3),)]

但是我想得到的是

cp1 = [(-1,-2,-3), (-1,-2,+3), (-1,+2,-3), (-1,+2,+3), ..., (+1,+2,-3), (+1,+2,+3)].

我尝试了一些不同的事情:

I have tried a few different things:

cp = list(itertools.product(itertools.islice(arrays, len(arrays))));
cp = list(itertools.product(iter(arrays, len(arrays))));

他们都给了我 cp0 而不是 cp1 .

有什么想法吗?

谢谢.

推荐答案

>>> list(itertools.product(*arrays))
[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]

这会将所有对作为单独的参数提供给product,这将为您提供它们的笛卡尔积.

This will feed all the pairs as separate arguments to product, which will then give you the cartesian product of them.

您的版本无法正常运行的原因是您仅给product一个参数.索要一个列表的笛卡尔积是很简单的情况,它返回一个仅包含一个元素的列表(该列表作为参数给出).

The reason your version isn't working is that you are giving product only one argument. Asking for a cartesian product of one list is a trivial case, and returns a list containing only one element (the list given as argument).

这篇关于如何将itertools.product应用于列表列表的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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