I have a simple list of list
a = [['A','10'],['B','30']]
How do I change it so that only those elements that can be converted into an integer is converted into an integer.
So I am hoping to get
a = [['A',10],['B',30]]
I have a simple list of list
a = [['A','10'],['B','30']]
How do I change it so that only those elements that can be converted into an integer is converted into an integer.
So I am hoping to get
a = [['A',10],['B',30]]
You can just use a try except block as follows.
def try_convert_int(val):
try:
return int(val)
except ValueError:
return val
a = [['A','10'],['B','30']]
out = [[try_convert_int(item) for item in row] for row in a]
print(out) #[['A', 10], ['B', 30]]