首页 > 解决方案 > 从输入文件中搜索数据类型

问题描述

我试图在包含浮点数和 int 值的输入列表中查找 int 值。问题是读入的列表如下所示:

List = [“14”,”8.00”,”2.00”,”3”]

我将如何在此列表中仅查找整数值,而不是浮点数?我假设 type 函数不起作用,因为它只会说所有数字都是字符串。

标签: pythonlistinput

解决方案


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']

推荐阅读