在比赛中配对人

时间:2012-12-20 11:36:59

标签: python combinations itertools

假设有一种比赛,其中有五个男孩和五个女孩:

boys = ["Boy1", "Boy2", "Boy3", "Boy4", "Boy5"]
girls = ["Girl1", "Girl2", "Girl3", "Girl4", "Girl5"]

每个男孩都被一个女孩吸引,他们玩游戏。什么是Pythonic方式(可能涉及itertools?)以产生所有对的所有组合?

例如,组合可以是:

combination1 = [("Boy1", "Girl1"), ("Boy2", "Girl2"), 
                ("Boy3", "Girl3"), ("Boy4", "Girl4"), ("Boy5", "Girl5")]

所以Boy1对抗Girl1等。如果Boy1被对阵Girl1,那么没有其他女孩可以对抗他。

3 个答案:

答案 0 :(得分:3)

from itertools import product

l1 = ["boy1","boy2","boy3"]
l2 = ["girl1","girl2","girl3"]

print list(product(l1,l2))

输出是:

[('boy1', 'girl1'), ('boy1', 'girl2'), ('boy1', 'girl3'), 
 ('boy2', 'girl1'), ('boy2', 'girl2'), ('boy2', 'girl3'), 
 ('boy3', 'girl1'), ('boy3', 'girl2'), ('boy3', 'girl3')]

答案 1 :(得分:2)

这应该可以解决问题:

shuffle给出了某种形式的随机性,男孩和女孩彼此配对

In [115]: boys = ["Boy1", "Boy2", "Boy3", "Boy4", "Boy5"]

In [116]: girls = ["Girl1", "Girl2", "Girl3", "Girl4", "Girl5"]

In [117]: random.shuffle(girls)

In [118]: girls
Out[118]: ['Girl5', 'Girl4', 'Girl3', 'Girl1', 'Girl2']

In [119]: for i in itertools.izip(boys, girls):
   .....:     print i
   .....:     
('Boy1', 'Girl5')
('Boy2', 'Girl4')
('Boy3', 'Girl3')
('Boy4', 'Girl1')
('Boy5', 'Girl2')

编辑:如果您想要所有可能的配对,请查看:

In [126]: boys
Out[126]: ['Boy1', 'Boy2', 'Boy3', 'Boy4', 'Boy5']

In [127]: girls
Out[127]: ['Girl1', 'Girl2', 'Girl3', 'Girl4', 'Girl5']

In [128]: [girls[i:]+girls[:i] for i in xrange(len(girls))]
Out[128]: 
[['Girl1', 'Girl2', 'Girl3', 'Girl4', 'Girl5'],
 ['Girl2', 'Girl3', 'Girl4', 'Girl5', 'Girl1'],
 ['Girl3', 'Girl4', 'Girl5', 'Girl1', 'Girl2'],
 ['Girl4', 'Girl5', 'Girl1', 'Girl2', 'Girl3'],
 ['Girl5', 'Girl1', 'Girl2', 'Girl3', 'Girl4']]

In [129]: for combo in (itertools.izip(boys, g) for g in ( girls[i:]+girls[:i] for i in xrange(len(girls)) )):
   .....:    for pair in combo:
   .....:        print pair,
   .....:    print ''
   .....:     
('Boy1', 'Girl1') ('Boy2', 'Girl2') ('Boy3', 'Girl3') ('Boy4', 'Girl4') ('Boy5', 'Girl5') 
('Boy1', 'Girl2') ('Boy2', 'Girl3') ('Boy3', 'Girl4') ('Boy4', 'Girl5') ('Boy5', 'Girl1') 
('Boy1', 'Girl3') ('Boy2', 'Girl4') ('Boy3', 'Girl5') ('Boy4', 'Girl1') ('Boy5', 'Girl2') 
('Boy1', 'Girl4') ('Boy2', 'Girl5') ('Boy3', 'Girl1') ('Boy4', 'Girl2') ('Boy5', 'Girl3') 
('Boy1', 'Girl5') ('Boy2', 'Girl1') ('Boy3', 'Girl2') ('Boy4', 'Girl3') ('Boy5', 'Girl4') 

编辑2 (修正编辑1):

>>> perms = itertools.permutations(girls)
>>> len([tuple(p) for p in (itertools.product(boys, g) for g in perms)])
120
>>> perms = itertools.permutations(girls)
>>> len(set(tuple(p) for p in (itertools.product(boys, g) for g in perms)))
120

我必须选择len,因为有120种可能的配对,我不想让这个帖子混乱。这就是len(...)len(set(...))

的原因

答案 2 :(得分:2)

另一个想法:

>>> zip(boys, random.sample(girls, len(girls)))
[('Boy1', 'Girl3'), ('Boy2', 'Girl2'), ('Boy3', 'Girl4'), ('Boy4', 'Girl1'), 
 ('Boy5', 'Girl5')]