All possible (monogamous) pairings of two lists (of boys and girls)

回眸只為那壹抹淺笑 提交于 2021-02-19 03:36:10

问题


I have these two lists:

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

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)

... which gives this output.

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

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

Sven's almost answer (with my enumerate addition)

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.


回答1:


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

prints

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


来源:https://stackoverflow.com/questions/8886680/all-possible-monogamous-pairings-of-two-lists-of-boys-and-girls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!