这应该可以解决问题:
洗牌提供了某种形式的随机性,男孩和女孩相互配对
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(...))