在下面的代碼中,我嘗試創建一個驗證點,以驗證所有輸入項是否都是浮點數(輸入 if 形式為“ 1,2,3,4,b,w,...”),但是我無法理解如何在不傷害串列本身的情況下執行此操作。想要的輸出是[1.0,2.0,3.0,4.0]當所有專案都是浮點數時,或者如果不只回答數字則為錯誤訊息。
list1_str = input("Enter list1: ")
list1_str1 = list1_str.replace(" ", "").split(",")
for i in list1_str1:
if list1_str1[i].isdigit:
break
else: print("item is not float")
list1 = [float(i) for i in list1_str1] #turn list to floats
我做錯了什么?
uj5u.com熱心網友回復:
您可以將其分為兩部分:1) 驗證輸入型別和 2) 如果正確,則轉換為數字型別:
def validate_list(my_list):
is_valid = all([j.isnumeric() for j in my_list])
return is_valid
def cast_numeric(my_list):
if not validate_list(my_list):
raise ValueError("non-numeric string value found")
else:
return [float(j) for j in my_list]
# examples:
l1 = list("12345")
l2 = l1 ["not a num"]
validate_list(l1) # true
cast_numeric((l1) # [1.0, 2.0, 3.0, 4.0, 5.0]
validate_list(l2) # false
cast_numeric((l2) # raises error message
uj5u.com熱心網友回復:
您的代碼中有一些錯誤。
isdigit不是一個屬性,它是一個方法,所以稱之為isdigit()- 您在回圈中設定了一個中斷,這是沒有必要的。
有關您想要做的某些版本的事情,請參閱以下代碼
list1_str = input("Enter list1: ")
list1_str1 = list1_str.replace(" ", "").split(",")
# This is enough to get all the float values.
numericals = [float(num) for num in list1_str1 if num.isdigit()]
# Let'say you want to print a validation message, then it can be
if not all([num.isdigit() for num in list1_str1]):
print("Invalid float items found")
#Let's say you want to print the invalid ones as well, then
wrong_ones = [num for num in list1_str1 if not num.isdigit()]
if wrong_ones and len(wrong_ones) > 0:
print(f"The items {wrong_ones} are invalid floats in input")
希望這對你來說有點清楚
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362329.html
