Python 如果可以转换,请映射

Python 如果可以转换,请映射,python,algorithm,list,casting,Python,Algorithm,List,Casting,我有以下清单: a = ['1', '2', 'hello'] 我想得到 a = [1, 2, 'hello'] 我的意思是,转换所有我能转换的整数 这是我的职责: def listToInt(l): casted = [] for e in l: try: casted.append(int(e)) except: casted.append(e) return casted 但是,我

我有以下清单:

a = ['1', '2', 'hello']
我想得到

a = [1, 2, 'hello']
我的意思是,转换所有我能转换的整数

这是我的职责:

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

但是,我可以使用
map()
函数或类似的功能吗?

确实可以使用
map

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

确实可以使用
map

def func(i):
    try:
        i = int(i)
    except:
        pass
    return i
a = ['1', '2', 'hello']
print(list(map(func, a)))
也许是这样的


也许是这样的

你的东西怎么了?我觉得不错。它是可读的,EAFP。没有问题。您可以在使用
map
@idjaw调用的函数中使用
try/except
,我认为这是正确的,但我想知道我是否可以按照Barmar的建议来做。只是一个小小的改进:
除了(ValueError,TypeError):
你的东西有什么问题?我觉得不错。它是可读的,EAFP。没有问题。您可以在使用
map
@idjaw调用的函数中使用
try/except
,我认为这是正确的,但我想知道我是否可以按照Barmar的建议来做。只是一个小小的改进:
除了(ValueError,TypeError):