user7970547
user7970547

Reputation: 147

Python generate tuple combination with criteria

Trying to generate a combination which excludes the combinations mentioned in c and am unsure of how to proceed.

a = [1.01, 5.84, 13.86]

b = [6.42,0,18.24]

c = [(1.01,18.24), (13.86,0), (5.84,0)]

combination = [(x,y) for x in a 

                     for y in b]

Intended Result: (1.01,6.42), (1.01,0), (5.84,6.42), (5.84,18.24), (13.86,6.42), (13.86,18.24)

Upvotes: 2

Views: 752

Answers (1)

Some Guy
Some Guy

Reputation: 1797

You can use itertools.product to generate combinations and then exclude them by comparison

from itertools import product
a = [1.01, 5.84, 13.86]
b = [6.42,0,18.24]
c = [(1.01,18.24), (13.86,0), (5.84,0)]

combs = list(product(a,b))

[(1.01, 6.42),
 (1.01, 0),
 (1.01, 18.24),
 (5.84, 6.42),
 (5.84, 0),
 (5.84, 18.24),
 (13.86, 6.42),
 (13.86, 0),
 (13.86, 18.24)]


new_combs = [x for x in combs if x not in c]

[(1.01, 6.42),
 (1.01, 0),
 (5.84, 6.42),
 (5.84, 18.24),
 (13.86, 6.42),
 (13.86, 18.24)]

Note: As noted in comments the list around combs is for demo so that you can see all the combinations. Instead you might want to do:

new_combs = [x for x in product(a,b) if x not in c]

More on tuple and list comparisons here: How does tuple comparison work in Python?

Tuples are compared position by position: the first item of first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

Also:
Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Upvotes: 1

Related Questions