一个明显的例子是XY problem。。。在
你真正的问题是错误的数据结构,以同样的方式存储异构信息(学生的姓名和标记)。RightSolution(tm)是使用更好的数据结构,即:student1 = {
"personal_infos" : {
"name": "Lloyd",
},
"marks": {
"homework": [90, 97, 75, 92],
"quiz": [88, 40, 94],
"test": [75, 90]
},
"totals": {}
"averages": {}
}
}
一旦有了这个,就不必测试是否有字符串或num作为值:
^{pr2}$
请注意,您可以用不同的方式布局数据,即每个主题:student1 = {
"personal_infos" : {
"name": "Lloyd",
},
"subjects": {
"homework": {
"marks" : [90, 97, 75, 92],
"total" : None,
"average" : None
},
"quiz": {
"marks" : [88, 40, 94],
"total" : None,
"average" : None
},
"test": {
"marks" : [75, 90],
"total" : None,
"average" : None
},
},
}
def eachSubjAverage(student):
for subject, data in student["subjects"].items():
total = sum(data["marks"]) #totalling each marks
data["total"] = total
average = total / (len(data["marks"]))
data["average"] = average
请注意,如果您无法选择修复数据结构(外部数据或其他),则您仍然不希望依赖类型检查(这充其量是脆弱的)-您希望测试密钥本身,方法是将主题名称白名单或将“非主题”名称列入黑名单,即:# blacklist non-subjects
NON_SUBJECTS = ("name",)
def your_func(student):
for key, value in student.items():
if key in NON_SUBJECTS:
continue
compute_stuff_here()
哦,是的:把总分和平均分加在分数表上也是一个很好的方法,一旦你做到了,你就不能告诉她最后两个“分数”是分数还是(总分,平均分)。在