验证所有输入项是否都是 Python 中的浮点数

Validation if all input items are floats in Python

在下面的代码中,我试图创建一个验证点来验证是否所有输入项都是浮点数(输入是否为“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

我做错了什么?

你的代码有一些错误。

  • 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")

希望这能让你明白一点

您可以将其分为两部分: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