簡體   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