Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

python - How to apply itertools.product to elements of a list of lists?

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 seems to do the trick but I am stuck in a little detail.

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

If I do

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

I get

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

But what I want to get is

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

They all gave me cp0 instead of cp1.

Any ideas?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> 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)]

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...