I'm trying to find int values in an inputted list that contains floats and int values. The problem is the list read in looks like this:
List = [“14”,”8.00”,”2.00”,”3”]
How would I go about finding just the integer values in this list, not the floats? I'm presuming the type function won't work since it'll just say all the numbers are strings.
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']
Try below code:
l = ["14","8.00","2.00","3"]
l = [int(i) for i in l if i.isdigit()]
print(l)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.