[英]Why variable replacement does not work in Python nested loop
我有以下代码:
lower_threshold = 6.33
upper_threshold = 1e+30
threshold_dict_by_patient_and_visit = {
"k2-01-003|15" : [15.007, 1e+30]
}
mylist = ['k2-01-003|18', 'k2-01-003|13','k2-01-003|15']
for i in range(3):
for patient_visit in mylist:
if (patient_visit in threshold_dict_by_patient_and_visit):
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit[patient_visit]
print(i, patient_visit, lower_threshold, upper_threshold)
我要完成的任务是这样的:
range(3)
循环中,循环遍历mylist
。threshold_dict_by_patient_and_visit
字典(在本例中为k2-01-003|15
)时,用该字典中的值替换lower_threshold
和upper_threshold
。 否则使用默认值: 6.33
和1e+30
我期望的结果是这样的:
0 k2-01-003|18 6.33 1e+30
0 k2-01-003|13 6.33 1e+30
0 k2-01-003|15 15.007 1e+30
1 k2-01-003|18 6.33 1e+30
1 k2-01-003|13 6.33 1e+30
1 k2-01-003|15 15.007 1e+30
2 k2-01-003|18 6.33 1e+30
2 k2-01-003|13 6.33 1e+30
2 k2-01-003|15 15.007 1e+30
为什么它会给出这个:
0 k2-01-003|18 6.33 1e+30
0 k2-01-003|13 6.33 1e+30
0 k2-01-003|15 15.007 1e+30
1 k2-01-003|18 15.007 1e+30
1 k2-01-003|13 15.007 1e+30
1 k2-01-003|15 15.007 1e+30
2 k2-01-003|18 15.007 1e+30
2 k2-01-003|13 15.007 1e+30
2 k2-01-003|15 15.007 1e+30
正确的做法是什么?
我正在使用 Python 3.8.5。
更新
我尝试添加else
但仍然不起作用:
for i in range(3):
for patient_visit in mylist:
if (patient_visit in threshold_dict_by_patient_and_visit):
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit[patient_visit]
else:
lower_threshold, upper_threshold = lower_threshold, upper_threshold
print(i, patient_visit, lower_threshold, upper_threshold)
threshold_dict_by_patient_and_visit = {
"k2-01-003|15" : (15.007, 1e+30) # using tuple instead of list because you don't need to mutate them; this is not mandatory
}
default_thresholds = (6.33, 1e+30)
mylist = ['k2-01-003|18', 'k2-01-003|13','k2-01-003|15']
for i in range(3):
for patient_visit in mylist:
#dict.get: get an item if it exists, otherwise return a default value
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit.get(patient_visit, default_thresholds)
print(i, patient_visit, lower_threshold, upper_threshold)
这是一个干净且有效的解决方案:
threshold_dict_by_patient_and_visit = {
"k2-01-003|15" : [15.007, 1e+30]
}
mylist = ['k2-01-003|18', 'k2-01-003|13','k2-01-003|15']
for i in range(3):
lower_threshold = 6.33
upper_threshold = 1e+30
for patient_visit in mylist:
if patient_visit in list(threshold_dict_by_patient_and_visit.keys()):
lower_threshold, upper_threshold = threshold_dict_by_patient_and_visit[patient_visit]
print(i, patient_visit, lower_threshold, upper_threshold)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.