我有这两份名单:
boys = [1,2,3]
girls = [1,2,3]你将如何建立所有可能的(一夫一妻制)配对[boy, girl]?boys和girls中只有3对,我认为这是所有可能的配对的列表:
[
[[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],你如何找到所有可能的配对(上面写的是特定的例子)?,这就像你必须用6种方法来乘3x3矩阵的元素(找到它的行列式)。:)
斯文的回答(加上我的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这完全符合问题的格式。
发布于 2012-01-16 21:45:32
你所描述的是集合的排列。让男孩们按给定的顺序排列,然后遍历女孩的所有排列--这将给你提供所有可能的配对:
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 b3g1https://stackoverflow.com/questions/8886680
复制相似问题