I have a list as below:
input_a= [['a','12','','23.5'],[12.3,'b2','-23.4',-32],[-25.4,'c']]
I want to convert the numbers in this to numbers to get an output like this
output_a = [['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]
I wrote the following code to get this to work:
def str_to_num(str_object=None):
if not isinstance(str_object,str):
return str_object
try:
x = int(str_object)
except ValueError:
try:
x = float(str_object)
except ValueError:
x =str_object
return x
def getNumbers(num_object=None,return_container=None):
a = return_container
if isinstance(num_object,list):
b = []
for list_element in num_object:
if isinstance(list_element,list):
x = getNumbers(list_element,a)
if isinstance(list_element,str):
y = str_to_num(list_element)
b += [y]
if isinstance(list_element,int):
y = list_element
b += [y]
if isinstance(list_element,float):
y = list_element
b += [y]
a += [b]
return return_container
return_container = []
output_a = getNumbers(input_a,return_container)[:-1]
This works (for this situation). But I have two problems: 1. It does not work so well if there is another level of nesting of list. I want to make it such that it can handle any level of nesting. so if
input_b= [['a','12','','23.5',['15']],[12.3,'b2','-23.4',-32],[-25.4,'c']]
This gives
output_b= [[-15],['a',12,'',23.5],[12.3,'b2',-23.4,-32],[-25.4,'c']]
which is wrong as the [-15] should be nested within the first sub-list.
- The code is very verbose!! I am sure there must be a much simpler way to handle this.