Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Find cartesian product of lists filtering out the elements based on condition

I recently came across this notation

a = [1,2,3,4]
b = [2,4,6]

c = [(x,y,z) for x in a for y in b for z in a]

First I don't know how to search for the notation in creating c, is there a name for this type of structure?

Also, I'm confident that c can be updated to not allow x to equal z. Please can you help me with this?

I've tried various things on the lines of

c = [(x,y,z) for x in a for y in b for z in a for x != z]

but so far I can't find anything that works, or is even valid syntax.

What I'm trying to accomplish is to find every combination of (a,b,a) where a can only be used once in each line so the result would be

[(1, 2, 2),
 (1, 2, 3),
 (1, 2, 4),
 (1, 4, 2),
 (1, 4, 3),
 (1, 4, 4),
 (1, 6, 2),
 (1, 6, 3),
 (1, 6, 4),
 (2, 2, 1),
 (2, 2, 3),
 (2, 2, 4),
 (2, 4, 1),
 (2, 4, 3),
 (2, 4, 4),
 (2, 6, 1),
 (2, 6, 3),
 (2, 6, 4),
 (3, 2, 1),
 (3, 2, 2),
 (3, 2, 4),
 (3, 4, 1),
 (3, 4, 2),
 (3, 4, 4),
 (3, 6, 1),
 (3, 6, 2),
 (3, 6, 4),
 (4, 2, 1),
 (4, 2, 2),
 (4, 2, 3),
 (4, 4, 1),
 (4, 4, 2),
 (4, 4, 3),
 (4, 6, 1),
 (4, 6, 2),
 (4, 6, 3)]

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It is known as list comprehension and you can use logical if within it to filter the results in the returned list as:

>>> a = [1,2,3,4]
>>> b = [2,4,6]
#     if condition to skip results where `x` equals `z` v
>>> c = [(x,y,z) for x in a for y in b for z in a if x != z]
>>> c   
[(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 6, 2), (1, 6, 3), (1, 6, 4), (2, 2, 1), (2, 2, 3), (2, 2, 4), (2, 4, 1), (2, 4, 3), (2, 4, 4), (2, 6, 1), (2, 6, 3), (2, 6, 4), (3, 2, 1), (3, 2, 2), (3, 2, 4), (3, 4, 1), (3, 4, 2), (3, 4, 4), (3, 6, 1), (3, 6, 2), (3, 6, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 6, 1), (4, 6, 2), (4, 6, 3)]

Instead of using nested list comprehension, you may get the same behavior using itertools.product as well:

>>> from itertools import product

>>> [(x,y,z) for x, y, z in product(a, b, a) if x !=z]
[(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 6, 2), (1, 6, 3), (1, 6, 4), (2, 2, 1), (2, 2, 3), (2, 2, 4), (2, 4, 1), (2, 4, 3), (2, 4, 4), (2, 6, 1), (2, 6, 3), (2, 6, 4), (3, 2, 1), (3, 2, 2), (3, 2, 4), (3, 4, 1), (3, 4, 2), (3, 4, 4), (3, 6, 1), (3, 6, 2), (3, 6, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 6, 1), (4, 6, 2), (4, 6, 3)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...