tdrd
tdrd

Reputation: 7

combining n elements of iterable1 with m elements of iterable2

how do i combine n items from iterable1 with m items from iterable2?

i.e.

iterable1 = [0,1,2,3,4]
iterable2 = ['a','b','c']
BlackBox(itertools.combination(iterable1, 2),itertools.combination(iterable2, 1)) yields
(0,1,'a'), (0,1,'b'), (0,1,'c'), (0,2,'a'), (0,3,'a'), etc. Order doesn't matter

I'm receiving a list of elements, which may contain a wildcard which I then need to replace with all of the wildcard's possible values. I check for the number of wildcards and need to add a combination of that many elements into my de-wildcarded list. In other words, iterable2 is all the possible values of the wildcard, m is the number of wildcards, iterable1 is the original list with all wildcards removed, and n is the number of desired items less m.

Upvotes: 0

Views: 215

Answers (1)

John La Rooy
John La Rooy

Reputation: 304375

>>> iterable1 = [0,1,2,3,4]
>>> iterable2 = ['a','b','c']
>>> import itertools as it
>>> list(x+y for x,y in it.product(it.combinations(iterable1, 2), it.combinations(iterable2, 1)))
[(0, 1, 'a'), (0, 1, 'b'), (0, 1, 'c'), (0, 2, 'a'), (0, 2, 'b'), (0, 2, 'c'), (0, 3, 'a'), (0, 3, 'b'), (0, 3, 'c'), (0, 4, 'a'), (0, 4, 'b'), (0, 4, 'c'), (1, 2, 'a'), (1, 2, 'b'), (1, 2, 'c'), (1, 3, 'a'), (1, 3, 'b'), (1, 3, 'c'), (1, 4, 'a'), (1, 4, 'b'), (1, 4, 'c'), (2, 3, 'a'), (2, 3, 'b'), (2, 3, 'c'), (2, 4, 'a'), (2, 4, 'b'), (2, 4, 'c'), (3, 4, 'a'), (3, 4, 'b'), (3, 4, 'c')]

Upvotes: 1

Related Questions