[英]How to go through a nested for loop?
您好,我试图使我的代码经过嵌套的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
您的return关键字位于外循环内。 这意味着man只会取值0,因此是您当前的输出。 下面的代码可实现所需的输出。
men_choice = [[1, 2, 3, 0], [3, 1, 2, 0], [2, 1, 3, 0], [3, 2, 0, 1]]
women_choice = []
def couple(men_choice, women_choice):
possible_engagements = []
for man in range(len(men_choice)):
possible_engagements.append((man, men_choice[man][0]))
return possible_engagements
possible_engagements = couple(men_choice, women_choice)
print(possible_engagements)
作为列表理解:
def couple(men_choice, women_choice):
return [(i, x[0]) for i, x in enumerate(men_choice)]
作为for-loop生成器:
def couple(men_choice, women_choice):
for i, x in enumerate(men_choice):
yield (i, x[0])
作为for循环+ list.append:
def couple(men_choice, women_choice):
engagements = []
for i, x in enumerate(men_choice):
engagements.append((i, x[0]))
return engagements
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.