python - 从输入文件中搜索数据类型
问题描述
我试图在包含浮点数和 int 值的输入列表中查找 int 值。问题是读入的列表如下所示:
List = [“14”,”8.00”,”2.00”,”3”]
我将如何在此列表中仅查找整数值,而不是浮点数?我假设 type 函数不起作用,因为它只会说所有数字都是字符串。
解决方案
you can use ast
module to identify the integer and float from strings.
In [16]: type(ast.literal_eval("3"))
Out[16]: int
In [17]: type(ast.literal_eval("3.0"))
Out[17]: float
Now using this concept with isinstance
, you can filter out the integers:
In [7]: import ast
In [10]: a = ['14','8.00','2.00','3']
In [11]: a
Out[11]: ['14', '8.00', '2.00', '3']
In [12]: res = []
In [13]: for num in a:
...: if isinstance(ast.literal_eval(num),int):
...: res.append(num)
...:
In [14]: res
Out[14]: ['14', '3']
推荐阅读
- r - JAGS 中的简单 SIR
- amazon-web-services - 如何使用亚马逊事件桥通过 sns 获取在 aws 参数存储中修改参数的用户的详细信息
- c++ - 如何在不显示 CMD 窗口的情况下在 C++ 中运行命令?
- html - 如何使用超脚本助手创建导航?
- python - 将 pd.series 与差异长度进行比较并仅显示差异值
- reactjs - React 项目在 Heroku 上因许多分配失败而崩溃,但在本地开发人员上运行
- javascript - 我们如何以角度向 DOM 元素(来自 ts 文件)注入属性指令
- javascript - 在 Vue.js 中使用 $state 的最佳方式是什么?
- python - Azure Durable 函数 python DurableOrchestrationContext get_input 返回 null
- java - 将数组打印到控制台时是否可以隐藏数组中的元素?