53

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

我将用一个例子来使这个更具体......

itertools.product 似乎可以解决问题,但我被困在一个小细节上。

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)].

我尝试了一些不同的东西:

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

他们都给了我cp0而不是cp1

有任何想法吗?

提前致谢。

4

3 回答 3

67
>>> 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,然后为您提供它们的笛卡尔积。

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).

于 2010-06-13T21:38:40.943 回答
40
>>> arrays = [(-1,+1), (-2,+2), (-3,+3)]
>>> 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)]
于 2010-06-13T21:41:14.090 回答
1

you can do it in three rurch using itertools.product

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

import itertools 

for i in itertools.product(*arrays):
         lst.append(i)



print(lst)

enter image description here

于 2020-05-15T15:21:09.330 回答