python - 如何在 Python 的另一个循环中正确编写一个 for 循环?
问题描述
我试图在尽可能多的迭代中循环现有的 for 循环,这样我就不必手动执行此操作。我的嵌套循环根据他们的偏好将医生与医院进行匹配。这里 get 函数中的 1.0 指的是 rank 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 轮使用 2。get(2.0)
这对于 10 位医生和 10 家医院的数据集是可行的。但是,我想增加此数据集的大小然后手动执行此操作变得不可持续。所以我想编写一个循环自动为我执行此操作,然后字典匹配应显示所有十轮以及在这些轮中获得的匹配。
range(len(free_doctors))
如果循环一直持续到所有医生和医院都匹配,甚至比使用, 更好。
解决方案
看起来你正在尝试解决“稳定的婚姻”问题。不是夫妻无法“交易”,而是医生和医院,但结构是一样的:学生和学校等。
https://gist.github.com/joyrexus/9967709是谷歌的第一个热门"Stable Marriage" Python
,它可能会做你想做的事。
推荐阅读
- java - 如何在android studio中的背景图像上显示gif
- angular - 以 Angular 形式提交
- javascript - 与多个 index.html 反应
- java - 装饰器模式可以用行为模式代替来解决问题吗?
- mongodb - 无法在项目上执行目标 io.swagger:swagger-codegen-maven-plugin:2.2.3:generate (default) 代码生成失败
- ios - 通知未收到 iOS
- firebase - 添加 Firebase 存储包后 Unity android 无法构建
- asp.net-mvc - asp.net mvc 应用程序中 bin\roslyn\csc.exe 中的 exe 文件不允许在托管服务器中使用。如何解决这个问题?
- reactjs - 如何在令牌过期时创建注销
- nginx - 无法将 keyrock 与未加载的 nginx、css 和 js 文件集成