gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:34 25 4
gpt4 key购买 nike

我正在尝试对现有的 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

免费医生:

['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 代表第 1 轮,get(1.0),并且2 使用 get(2.0) 进行第 2 轮。这对于 10 名医生和 10 家医院的数据集是可行的。但是,我想增加该数据集的大小,然后手动执行此操作变得不可持续。所以我想编写一个循环来自动为我执行此操作,然后字典 Matches 应该显示所有十轮以及在这些轮中获得的比赛。

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

最佳答案

看来您正在努力解决“稳定婚姻”问题。不再是丈夫和妻子无法“交易”,而是有医生和医院,但结构是一样的:学生和学校等。

https://gist.github.com/joyrexus/9967709是 Google 首次推出的“稳定婚姻”Python,它可能会满足您的需求。

关于python - 如何在Python中的另一个循环中正确编写一个for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com