FacundoGFlores FacundoGFlores - 2 months ago 6
Python Question

Map if it can be converted

I have the following list:

a = ['1', '2', 'hello']


And I want to obtain

a = [1, 2, 'hello']


I mean, convert all integers I can.

This is my function:

def listToInt(l):
casted = []
for e in l:
try:
casted.append(int(e))
except:
casted.append(e)
return casted


But, can I use the
map()
function or something similar?

Answer

Sure you can do this with map

def func(i):
    try:
        i = int(i)
    except:
        pass
    return i
a = ['1', '2', 'hello']
print(list(map(func, a)))