python-3.x - 如何检查字典中嵌套列表中的项目是否为浮点数?
问题描述
我目前正在尝试做一些类似计算器的事情,其中无效的输入会产生错误。出于本练习的目的,列表中的每个项目都用空格分隔。split() 但是,如果输入是浮点数,我会遇到问题。
我无法导入任何库
def get_valid_numbers(exprlist):
for n, token in enumerate(exprlist):
if token.isalpha():
print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n])} and {' '.join(exprlist[n+1:])} but {exprlist[n]} is a variable")
return False
if token != float and token not in '(+-**//)':
print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])}")
return False
return True
我输入了一个浮点数,但它仍然返回错误消息
def main():
while True:
expr = input('Enter expression: ')
if expr == '':
print('Application ended')
break
exprlist = expr.split()
if get_valid_numbers(exprlist):
eval(expr)
else:
continue
预期的输出是程序将检查令牌是否不是浮点数或不包含运算符和操作数之一“(+-**//)”。如果它是浮点数或包含运算符或操作数之一,则应返回 True
解决方案
检查类型应使用isinstance()
. 例如:
a = 5.4
isinstance(a, float)
>>> True
您还可以使用 . 检查类型type()
。例如:
b = 2
type(b) is float
>>> False
isinstance()
是首选的使用方法。
推荐阅读
- azure - 在 Azure Application Insights 中查看零视图的 Azure Web 应用页面
- javascript - 在 JavaScript 中,命名事件处理程序是否比匿名事件处理程序消耗更多内存?
- dask - 使用 Dask 将大型 csv 转换为镶木地板 - OOM
- html - 转换为 PDF 时停止 HTML 表“分页”(分页符?)到下一页
- karate - 空手道执行陷入报告生成步骤
- ios - SwiftUI 无法绑定注入的值
- javascript - 为什么我的 cdn 文件不能在浏览器中运行?
- javascript - 选中输入单选后单击按钮
- java - 在 Gridlayout Java Swing 中显示数组列表项
- c# - c# 中的静态方法只返回一个布尔值?