2

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)

user7970547
  • 147
  • 1
  • 14

1 Answers1

1

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.

Some Guy
  • 1,787
  • 11
  • 15
  • Nice answer! If you want to, you can also leave out the `list` wrapper around `combs` so you can lazily iterate over it in your final comprehension, which would be a bit more memory efficient, if the input lists are very large. – user3483203 Aug 17 '18 at 20:29
  • @user3483203 what do you mean? [ ] should be ignored at new_combs – user7970547 Aug 17 '18 at 20:40
  • The edit you made is what I was referring to. By directly iterating over `product(a, b)`, you are being more memory efficient. – user3483203 Aug 17 '18 at 20:41