python -检查用户输入的两个数字列表是否只包含数字(所有类型,包括分数和负数)



(在Python 3中)我需要检查输入(来自用户的两个数字列表)是否只包含数字,然后计算pearson相关性。分为需求:-所有类型的数字,包括分数和负数。-用户可以输入额外的空格或没有空格,它不应该测量。数字之间必须有逗号。-需要简单,没有库或高级函数。-如果来自用户的列表中的元素不是数字,他需要看到消息:"无法计算相关性";然后代码停止

我得到的线索:

有两种解决方法:

  1. 使用:以,strip,split开头-也可以用逗号分隔。如果你想在这一点之前和之后分解它是可能的。所有和列表的理解-需要创造力。2.运行数字的字符(使用for),并确保所有内容都是数字,并允许中间有一个点。

输出示例输入列表1:1,2,3,5,8输入清单2:0.11,0.1,0.13,0.2,0.18列表之间的相关性为:0.83

感谢我试图转换所有的浮点数,但如果它包含的东西不是一个数字我得到一个错误。我必须能够得到像0.18等这样的片段

list1=input("Enter list1:")
#Creates a list from string input
list1=list1.split(",")
#Check if all elements in list1 are numbers
check_list1_num = all(ele1.isdigit() for ele1 in list1)
#Same process for list2
list2=input("Enter list2:")
list2=list2.split(",")
check_list2_num = all(ele2.isdigit() for ele2 in list2)
if check_list1_num==True and check_list2_num==True:
list1 = [ float(i) for i in list1 ]
list2 = [ float(k) for k in list2]

如果用户

给出任何意外输入,则必须使用Try和except语句。
try:
list1=input("Enter list 1")
list2=input("Enter list 2")
lst1=list(map(float,[x.strip() for x in list1.split(',')]))
lst2=list(map(float,[x.strip() for x in list2.split(',')]))
corelation_function(list1,list2)
except Exception as e:
print("was not able to calculate the correlation")

在这里,我们将输入分割并从两侧去掉空白,然后将其转换为浮动。任何错误都将引发异常,代码将停止。

最新更新