繁体   English   中英

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

[英]How to properly write a for loop, within another loop in Python?

我正在尝试通过尽可能多的迭代循环现有的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轮使用1;对于第2轮,使用get(2.0) ,对于第2轮,这是可行的。一个由10位医生和10家医院组成的数据集,但是,我想增加此数据集的大小,然后手动执行此操作变得不可持续。因此,我想编写一个自动为我执行此操作的循环,然后词典Matches应该显示全部十轮比赛,并在那轮比赛中取得比赛。

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

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

https://gist.github.com/joyrexus/9967709是Google推出的"Stable Marriage" Python的首款产品,它可能会做您想要的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM