2016-09-20 41 views
0

我有以下列表:地图是否可以转换

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()功能或类似的东西?

+1

你有什么问题?对我来说看起来很好。它是可读的,EAFP。它没有错。 – idjaw

+0

您可以在'map'调用的函数中使用'try/except'。 – Barmar

+0

@idjaw我认为这是正确的,但我想知道如果我能做到这一点,因为Barmar建议 – FacundoGFlores

回答

3

当然,你可以用map

def func(i): 
    try: 
     i = int(i) 
    except: 
     pass 
    return i 
a = ['1', '2', 'hello'] 
print(list(map(func, a))) 
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 

也许是这样做呢?

相关问题