Reputation: 75
my_list=[['A','B','C','0.0'],['D','E','F','1.2'],['G','H','I','0'],['J','K','L','M']]
I tried these but they can only convert whole numbers into floats and leaves the rest as strings.
[[float(x) if x.isnumeric() else x for x in i] for i in my_list]
for i, sublist in enumerate(my_list):
for j, x in enumerate(sublist):
if x.isnumeric():
my_list[i][j] = float(x)
Expected output
[['A','B','C',0.0],['D','E','F',1.2],['G','H','I',0],['J','K','L','M']]
Upvotes: 0
Views: 98
Reputation: 5615
.isnumeric
does not return True
for float numbers represented as strings. It returns true for strings that only consists of numbers, .
is not a number.
This is why your solution only converts integers, not floats.
The best choice to check if a string is a float, and hence convert it - is to just try float()
and catching the raised ValueError
and simply continuing.
If you know the nesting is only one level deep, deceze's solution should do it great.
If there may be more nesting, you could try a recursive function-
def convert_float(l: list):
for i, v in enumerate(l):
if type(v) == list:
convert_float(v)
continue
try:
l[i] = float(v)
except ValueError:
continue
Upvotes: 0
Reputation: 34046
You can also use regex
to find this. Something like below:
In [105]: import re
In [106]: r = re.compile(r"^\d*[.,]?\d*$")
In [107]: [[float(v) if r.match(v) else v for v in l] for l in my_list]
Out[107]:
[['A', 'B', 'C', 0.0],
['D', 'E', 'F', 1.2],
['G', 'H', 'I', 0.0],
['J', 'K', 'L', 'M']]
Upvotes: 0
Reputation: 522032
If you have no other criterion than "anything might or mightn't be a valid float", then just try
them all:
def try_float(value):
try:
return float(value)
except ValueError:
return value
result = [[try_float(v) for v in l] for l in my_list]
Upvotes: 2