I'm trying to do some combinatorial stuff with data in Python. I looked the question How to generate all permutations of a list in Python, but think that doesn't fit my needs.. I have data of this type...:
group1-Steve
group1-Mark
group1-Tom
group2-Brett
group2-Mick
group2-Foo
group3-Dan
group3-Phil
...and i need to make all possible combinations of three elements with only one from each group, without repetitions, saving to a list every combination.
I know in this case there are 18 possible different combinations(3*3*2=18), but don't know how could i write this code. I ve read about the Pyncomb package, but don't know the function to apply in this case; maybe there's a function which does the job.
Hope anyone could help me...
Thanks in advance;
Peixe
The easiest way is to use itertools.product()
:
group1 = ["Steve", "Mark", "Tom"]
group2 = ["Brett", "Mick", "Foo"]
group3 = ["Dan", "Phil"]
for x in itertools.product(group1, group2, group3):
print x
prints
('Steve', 'Brett', 'Dan')
('Steve', 'Brett', 'Phil')
('Steve', 'Mick', 'Dan')
('Steve', 'Mick', 'Phil')
('Steve', 'Foo', 'Dan')
('Steve', 'Foo', 'Phil')
('Mark', 'Brett', 'Dan')
('Mark', 'Brett', 'Phil')
('Mark', 'Mick', 'Dan')
('Mark', 'Mick', 'Phil')
('Mark', 'Foo', 'Dan')
('Mark', 'Foo', 'Phil')
('Tom', 'Brett', 'Dan')
('Tom', 'Brett', 'Phil')
('Tom', 'Mick', 'Dan')
('Tom', 'Mick', 'Phil')
('Tom', 'Foo', 'Dan')
('Tom', 'Foo', 'Phil')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With