3

我有这两个列表:

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

你将如何建立所有可能的(一夫一妻制)配对[boy, girl]?只有 3 个boysgirls,我认为这是所有可能配对的列表:

[
 [[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]]
]

一般来说,你会怎么做(上面的格式)?这就是我能够提出的......

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 种方法。:)

斯文几乎回答(我的enumerate补充)

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

这完全满足问题中的格式。

4

1 回答 1

10

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

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
于 2012-01-16T21:45:32.773 回答