0

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

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

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

例如,组合可以是:

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

所以 Boy1 与 Girl1 对战,以此类推。如果 Boy1 与 Girl1 打成平局,则没有其他女孩可以与他对战。

4

3 回答 3

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')]
于 2012-12-20T11:48:45.350 回答
2

这应该可以解决问题:

洗牌提供了某种形式的随机性,男孩和女孩相互配对

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(...))

于 2012-12-20T11:40:19.463 回答
2

另一个想法:

>>> zip(boys, random.sample(girls, len(girls)))
[('Boy1', 'Girl3'), ('Boy2', 'Girl2'), ('Boy3', 'Girl4'), ('Boy4', 'Girl1'), 
 ('Boy5', 'Girl5')]
于 2012-12-20T11:42:43.223 回答