Reputation: 51
I have list of numbers as str
li = ['1', '4', '8.6']
if I use int
to convert the result is [1, 4, 8]
.
If I use float
to convert the result is [1.0, 4.0, 8.6]
I want to convert them to [1, 4, 8.6]
I've tried this:
li = [1, 4, 8.6]
intli = list(map(lambda x: int(x),li))
floatli = list(map(lambda x: float(x),li))
print(intli)
print(floatli)
>> [1, 4, 8]
>> [1.0, 4.0, 8.6]
Upvotes: 3
Views: 20107
Reputation: 1017
You can try map
each element using loads
from json
:
from json import loads
li = ['1', '4', '8.6']
li = [*map(loads,li)]
print(li)
# [1, 4, 8.6]
Or using eval()
:
print(li:=[*map(eval,['1','4','8.6','-1','-2.3'])])
# [1, 4, 8.6, -1, -2.3]
Notes:
Using
json.loads()
orast.literal_eval
is safer thaneval()
when the string to be evaluated comes from an unknown source
Upvotes: 0
Reputation: 11347
You're going to need a small utility function:
def to_float_or_int(s):
n = float(s)
return int(n) if n.is_integer() else n
Then,
result = [to_float_or_int(s) for s in li]
Upvotes: 1
Reputation: 2460
You can use ast.literal_eval
to convert an string to a literal:
from ast import literal_eval
li = ['1', '4', '8.6']
numbers = list(map(literal_eval, li))
As @Muhammad Akhlaq Mahar noted in his comment, str.isidigit
does not return True
for negative integers:
>>> '-3'.isdigit()
False
Upvotes: 1
Reputation: 5167
One way is to use ast.literal_eval
>>> from ast import literal_eval
>>> spam = ['1', '4', '8.6']
>>> [literal_eval(item) for item in spam]
[1, 4, 8.6]
Word of caution - there are values which return True with str.isdigit() but not convertible to int or float and in case of literal_eval will raise SyntaxError.
>>> '1²'.isdigit()
True
Upvotes: 1
Reputation: 1083
Convert the items to a integer if isdigit()
returns True
, else to a float. This can be done by a list generator:
li = ['1', '4', '8.6']
lst = [int(x) if x.isdigit() else float(x) for x in li]
print(lst)
To check if it actually worked, you can check for the types using another list generator:
types = [type(i) for i in lst]
print(types)
Upvotes: 8