问题描述
我有一个数组列表,我想获取数组中元素的笛卡尔积.
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应用于列表列表的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!