Reputation: 318
I am working on a program and I am having a bit of difficulty trying to figure about to make the for loop do what I would like.
As of right now, the for statement goes through every single combination of all lists and makes 5 choices, that is right, I want 5 choices.
However, it creates a lot of overlap, since I am adding all the lists together and picking 5 items. I do get what I want, but along with many combinations I do not, since all I am doing is adding all 5 lists together, I want them to be picked independently.
I would like the for statement to only go through each list row by row, and pick all combinations, with no overlap.
from itertools import combinations
.
.
.
.
def playerpick():
P1 = [1,2,3,4,7]
P2 = [1,8,13,14,17,29]
P3 = [1,2,3]
P4 = [1,7,8,12,15]
P5 = [1,2,3,4]
all_lists = P1 + P2 + P3 + P4 + P5
for (a,b,c,d,e) in combinations(all_lists, 5):
pick1 = a
pick2 = b
pick3 = c
pick4 = d
pick5 = e
playerpick()
The output I want is something like this, pull each item out from each list, one at a time:
output 1: [1,1,1,1,1]
output 2: [2,1,1,1,1]
output 3: [3,1,1,1,1]
output 4: [4,1,1,1,1]
output 5: [7,1,1,1,1]
output 6: [1,8,1,1,1](next combination)
output 7: [2,8,1,1,1]
output 8: [3,8,1,1,1]
output 9: [4,8,1,1,1]
output 10: [7,8,1,1,1]
output 11: [1,13,1,1,1](next combination)
output 12: [2,13,1,1,1]
...
Let me know if you have any questions, this is difficult to explain, I know.
Upvotes: 0
Views: 201
Reputation: 421
This cartesian product shall do it in the order you want:
import itertools
import pprint
def cartesian_product(lists):
return list(itertools.product(*lists))
for list in [(P1,P2,P3,P4,P5)]:
print(list, '=>')
pprint(cartesian_product(list), indent=2)
The cartesian product has no duplicates unless your input lists do, if it's the case maybe think of using set().
Upvotes: 1
Reputation: 34086
Since its a iterator, you can use next
:
In [240]: x = itertools.product(*a)
In [241]: next(x)
Out[241]: (1, 4, 7)
In [242]: next(x)
Out[242]: (1, 4, 8)
And so on.
You can have this next
in your function which will yield one combination at a time.
Upvotes: 2