所有可能的(一夫一妻制)两个名单(男孩和女孩)的配对

Bla*_*laz 3 python list python-itertools

我有这两个清单:

boys  = [1,2,3]
girls = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

你将如何建立所有可能的(一夫一妻制)配对[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]]
]
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

...给出了这个输出.

[1, 1] [1, 2] [1, 3]
[2, 1] [2, 2] [2, 3]
[3, 1] [3, 2] [3, 3]
Run Code Online (Sandbox Code Playgroud)

您如何找到所有可能的配对(上面为特定示例写出)?这些就像你需要将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
Run Code Online (Sandbox Code Playgroud)

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

Sve*_*ach 10

你所描述的是一组的排列.只需让男孩按照给定的顺序,并通过女孩的alll排列迭代 - 这将给你所有可能的配对:

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
Run Code Online (Sandbox Code Playgroud)

版画

b1g1 b2g2 b3g3
b1g1 b2g3 b3g2
b1g2 b2g1 b3g3
b1g2 b2g3 b3g1
b1g3 b2g1 b3g2
b1g3 b2g2 b3g1
Run Code Online (Sandbox Code Playgroud)