开发者

Python combinatorials w/o repetition - Pyncomb?

开发者 https://www.devze.com 2023-03-10 07:54 出处:网络
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'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')


Another alternative which avoids the import is to use a list comprehension:

[(a, b, c) for a in group1 for b in group2 for c in group3]

This gives the same result as Sven's but is nice if you want to do some filtering too.

0

精彩评论

暂无评论...
验证码 换一张
取 消