本文介绍了两个列表(男孩和女孩)的所有可能(一夫一妻)配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个列表:

boys  = [1,2,3]
girls = [1,2,3]

您将如何建立所有可能的(一夫一妻)配对? boysgirls都只有3个,我认为这是 all 可能配对的列表:

How would you build all possible (monogamous) pairings [boy, girl]? With only 3 of both boys and girls, I think this is the list of all the possible pairings:

[
 [[1,1], [2,2], [3,3]],
 [[1,1], [2,3], [3,2]],
 [[1,2], [2,1], [3,3]],
 [[1,2], [2,3], [3,2]],
 [[1,3], [2,1], [3,2]],
 [[1,3], [2,2], [3,1]]
]

您总体上会如何做(采用上述格式)?这就是我能够提出的...

How would you do it in general (in above format)? This is what I've been able to come up ...

pairs = list(itertools.product(boys, girls))
possible_pairings = []
for i, p in enumerate(pairs):
    if i % len(boys) == 0:
        print
    print list(p),
#   possible_pairings.append(pairing)

...给出此输出.

[1, 1] [1, 2] [1, 3]
[2, 1] [2, 2] [2, 3]
[3, 1] [3, 2] [3, 3]

如何找到所有可能的配对(上面为特定示例写出)?这些就像您必须将3x3矩阵的元素相乘(找到其行列式)的6种方式一样. :)

How would you find all possible pairings (written out above for specific example)? These are like the 6 ways you'd have to multiply elements of a 3x3 matrix (to find its determinant). :)

possible_pairings = []
possible_pairings_temp = []
boys  = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]

for girls_perm in itertools.permutations(girls):
    for i, (b, g) in enumerate(zip(boys, girls_perm)):
        possible_pairings_temp.append([b, g])
        if (i + 1) % len(boys) == 0: # we have a new pairings list
            possible_pairings.append(possible_pairings_temp)
            possible_pairings_temp = []
    print

print possible_pairings

这完全满足了问题的格式.

And this completely satisfies the format in the question.

推荐答案

您要描述的是集合的排列.只需按照给定的顺序离开男孩,然后遍历女孩的所有排列-这将为您提供所有可能的配对:

What you are describing are the permutations of a set. Simply leave the boys in the given order, and iterate through alll permutations of the girls -- this will give you all possible pairings:

boys = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]
for girls_perm in itertools.permutations(girls):
    for b, g in zip(boys, girls_perm):
        print b + g,
    print

打印

b1g1 b2g2 b3g3
b1g1 b2g3 b3g2
b1g2 b2g1 b3g3
b1g2 b2g3 b3g1
b1g3 b2g1 b3g2
b1g3 b2g2 b3g1

这篇关于两个列表(男孩和女孩)的所有可能(一夫一妻)配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:31