[英]Python : How to properly implement a raise an exception in a function
我正在嘗試制作一個 function 來接收列表/數組並返回該序列中最大值的索引。 如果列表中存在非數值,則 function 應該引發異常。
def maxvalue(values):
"""
Function that receives a list/array and returns the index of the maximum
value in that sequence
"""
indices = []
max_value = max(values)
for i in range(len(values)):
if type(i) not in (float, int): # raise an exception if the value is not float or integer
raise TypeError("Only numberical values are allowed")
if values[i] == max_value:
indices.append(i)
return indices
maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220])
function 在收到包含浮點數和整數的列表時起作用,如果其中有字符串則不起作用。
當列表中存在 str 時,如何讓 function 產生“TypeError("Only numberal values are allowed")”錯誤引用?
目前,它會產生“TypeError: '>' not supported between instances of 'str' and 'float'”
“比較”發生在最大 function 中,這會引發異常。
你應該在你的邏輯之前做所有的檢查。
def maxvalue(values):
"""
Function that receives a list/array and returns the index of the maximum
value in that sequence
"""
try:
max_value = max(values)
except TypeError:
raise TypeError("Only numberical values are allowed")
indices = []
for idx, val in enumerate(values):
if val == max_value:
indices.append(idx)
return indices
如您所見,我正在捕獲 TypeError 並用不同的消息重新引發它。 還可以在 for 循環中使用枚舉。
def maxvalue(values):
indices = []
print(values)
int_values = []
"""the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value"""
for x in values:
if type(x)==int:
int_values.append(x)
max_value = max(int_values)
for i in range(len(int_values)):
if int_values[i] == max_value:
indices.append(i)
return indices
print(maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.