-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
  • 19,076
  • 4
  • 25
  • 52
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
  • 5,814
  • 2
  • 12
  • 31