[英]Python: How to check the data type of key-value pair of an object?
我正在創建一個函數來在對象(student1)中添加每個數組(作業、測驗、測試)的標記。 當代碼嘗試添加“Lloyd”時,肯定會出現錯誤。 我要檢查的數據類型的“名稱”值,以進行算術運算僅當鍵的值是數字。 請建議。
student1 = {
"name": "Lloyd",
"homework": [90, 97, 75, 92],
"quiz": [88, 40, 94],
"test": [75, 90]
}
def eachSubjAverage(std):
for item in std:
total = sum(std[item]) #totalling each marks
std[item].append(total)
average_no = total/(len(std[item])-1) #averaging the marks
std[item].append(average_no)
eachSubjAverage(student1)
一個明顯的XY 問題案例......
您真正的問題是錯誤的數據結構,它以相同的方式存儲異類信息(學生的姓名及其分數)。 RightSolution(tm) 是使用更好的數據結構,即:
student1 = {
"personal_infos" : {
"name": "Lloyd",
},
"marks": {
"homework": [90, 97, 75, 92],
"quiz": [88, 40, 94],
"test": [75, 90]
},
"totals": {}
"averages": {}
}
}
一旦你有了這個,你就不必測試你是否有一個 string 或 num 作為值:
def eachSubjAverage(student):
for subject, marks in student["marks"].items():
total = sum(marks) #totalling each marks
student["totals"][subject] = total
average = total / (len(marks))
student["averages"][subject] = average
請注意,您可以以不同的方式布局數據,即每個主題:
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()
哦,是的:在分數列表中添加總分和平均分也是一個很好的辦法——一旦完成,你就分不清最后兩個“分數”是分數還是(總分,平均分)。
for item in std:
if isinstance(std[item],list):
total = sum(std[item])
如果要確保列表中的元素是int
類型,則
for item in std:
if isinstance(std[item],list) and all(isinstance(e,int) for e in student1[item]):
total = sum(std[item])
了解isinstance()方法
有幾種方法可以檢查數據的值。 try/except
構造看起來很笨重,但還有更多更短的方法。
首先,您可以使用函數type
,它返回您的對象類型:
>>> type(student1['name']) == str
True
>>> type(student1['test']) == list
True
或者,使用一個非常簡單的技巧。 將任何對象乘以零返回一個空對象或 0 如果int
:
>>> student1['name']*0 == ""
True
>>> student1['test']*0 == []
True
>>> student1['test'][1]*0 == 0
True
您可以檢查該值是否可迭代:
hasattr(std[item], '__iter__')
然后檢查每個成員是否是一個Number :
all( map ( lambda x: isinstance(x,numbers.Number), std[item] ) )
您可以try except
使用以下方法:
for item in std:
try:
total = sum(std[item])
except TypeError:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.