-1

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]]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Jim
  • 9
  • 1

1 Answers1

3

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]]
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33