映射是否可以转换

时间:2016-09-20 19:13:37

标签: 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

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

2 个答案:

答案 0 :(得分:3)

当然,您可以使用map

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

答案 1 :(得分:2)

a = ['1', '2', 'hello']
y = [int(x) if x.isdigit() else x for x in a]
>> [1, 2, 'hello']
>> #tested in Python 3.5

也许是这样的?