python - 如何通过嵌套的for循环?
问题描述
您好我正在尝试让我的代码通过嵌套的 for 循环,但循环拒绝遵循我最初的想法。
我的代码如下所示。
def couple(men_choice, women_choice):
possible_engagements = []
# men's first choice
for man in range(len(men_choice)):
for woman in men_choice:
pair = (man, woman[0])
possible_engagements.append(pair)
return possible_engagements
我正在尝试设计 Gale shapley 算法的第一步,在该算法中,每个男人都将与每个列表中的首选女人配对。
例如,如果我有
>>> men_choice = [[1, 2, 3, 0], [3, 1, 2, 0], [2, 1, 3, 0], [3, 2, 0, 1]]
possible_engagements = [(0, 1), (0, 3), (0, 2), (0, 3)] # current output
possible_engagements = [(0, 1), (1, 3), (2, 2), (3, 3)] # desired output
男性的首选女性正在按我的计划输出,但男性的指数没有按顺序排列。
我的循环有什么问题?
解决方案
您只需要一个 for 循环来检查男士的选择,并确保您没有重复的匹配项,您必须检查该女士是否已经与另一个男士配对。
def couple(men_choice, women_choice):
possible_engagements = []
# men's first choice
for man in range(len(men_choice)):
i = 0
pair = (man, men_choice[i])
while ([x[1] for x in possible_engagements].count(men_choice[i]) > 0): #Check if woman is already chosen
pair = (man, men_choice[i])
i=i+1
possible_engagements.append(pair)
return possible_engagements