2016-09-20 40 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 

也許是這樣做呢?

相關問題