如何在Python的另一个循环中正确编写for循环?

时间:2019-01-28 20:22:33

标签: python loops dictionary for-loop matching

我正在尝试通过尽可能多的迭代循环现有的for循环,这样我就不必手动执行此操作。我的嵌套循环根据医生和医生的偏好将它们匹配到医院。这里的get函数中的1.0指的是等级1。

这是我到目前为止所想的(代码中的#进行了更多解释):

def hospital_ranking_of_doctor(hospital, doctor):
    return ranking_by_hospitals2[hospital][doctor]

#free_doctors is currently a range (0,10)
for i in range(len(free_doctors)):
    #Make a dictionary with name Round_(i+1) (To start at Round_1)
    Round_(str(i+1)) = {}
    #Start off with same values as last round, this action should not be performed in the first round
    Round_(str(i+1)).update(Round_(str(i))
    Round_(str(i+1))_values = list(Round_(str(i+1)).values())
    for Doctor_ in ranking_by_doctors:
        favored_hospital = ranking_by_doctors[Doctor_].get(1.0 + i) #Hospitals are ranked from 1.0 - 10.0, need 1.0 or would start at 0 and get error
        favored_hospital_doctor = Doctor_
#If the hospital and doctor have not been assigned to a match before, assign the current hospital to the current doctor
        if favored_hospital not in Round_(str(i+1)) and favored_hospital_doctor not in Round_(str(i+1))_values:
                Round_(str(i+1))[favored_hospital] = Doctor_
#If the doctor has been assigned to a match before, continue with the next doctor
    elif favored_hospital_doctor in Round_(str(i+1))_values:
        continue
#If the hospital has been assigned to a match before, check if the previously assigned doctor is ranked higher (e.g 2.0 instead of 1.0)
#When this is indeed the case, the hospital prefers the new doctor over the old doctor, so assign the new doctor as its match    
    else:
        previously_assigned_doctor = Round_(str(i+1))[favored_hospital]
        if hospital_ranking_of_doctor(favored_hospital, previously_assigned_doctor) > hospital_ranking_of_doctor(favored_hospital, Doctor_):
            Round_(str(i+1)[favored_hospital] = Doctor_
Matches['Round_'str(i+1)] = Round_(str(i+1))
Matches

free_doctors:

['Doctor_10', 'Doctor_6', 'Doctor_5', 'Doctor_9', 'Doctor_1', 'Doctor_4', 'Doctor_3', 'Doctor_7', 'Doctor_2', 'Doctor_8']

嵌套的for循环可以工作,但是循环循环会给我带来语法错误。 (str(i+1)到处显示的位置(我会在新的命令代码中手动输入之前的数字(因此,对于第1轮,get(1.0)使用1,对于第2轮,get(2.0)使用2)。这是可行的对于由10位医生和10家医院组成的数据集,但是,我想增加此数据集的大小,然后手动执行此操作变得不可持续。因此,我想编写一个自动为我执行此操作的循环,然后字典Matches应该显示所有十回合以及在这些回合中达到的比赛。

如果循环一直持续到所有医生和医院都匹配好了,那比使用range(len(free_doctors))更好。

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试解决“稳定婚姻”问题。您拥有医生和医院,而不是丈夫和妻子无法“换身”,但结构是相同的:学生和学校等。

https://gist.github.com/joyrexus/9967709是Google在"Stable Marriage" Python上的第一支热门歌曲,它可能会做您想要的事情。