2017-10-17 42 views
-1

我在這裏看到了各種答案,但沒有一個回答我的問題。我想下面的列表將字符串列表轉換爲可能的整數

list = ['A', '2', '8', 'B', '3'] 

轉換爲以下幾點:

list = ['A', 2, 8, 'B', 3] 

我想保持串爲字符串,但是轉換字符串整數如果可能的話。

我知道我可以做這樣的事情:

list = [int(i) for i in list] 

如果只是數字,但我不確定如何做到這一點時,它是混合的。

+2

最好不要陰影保留的名稱像'list'。 –

回答

2

您可以使用str.isdigit()

>>> l = ['A', '2', '8', 'B', '3'] 
>>> [int(x) if x.isdigit() else x for x in l] 
['A', 2, 8, 'B', 3] 

以負數到:

>>> l = ['A', '2', '8', 'B', '-3'] 
>>> [int(x) if x.isdigit() or x.startswith('-') and x[1:].isdigit() else x for x in l] 
>>> ['A', 2, 8, 'B', -3] 
+3

這對於負數不起作用。 – wds

+2

@ wds的例外是你爲什麼一般比[LBYL]更喜歡[EAFP](https://docs.python.org/3/glossary.html#term-eafp)模式(https://docs.python.org/3 /glossary.html#term-lbyl);嘗試做你想做的事情,如果失敗則處理異常。不要試圖編寫一個解析器來預先檢查你的條件(你每次都會錯過一個邊緣案例),只要這樣做,並適當地處理失敗。 'int()'知道如何解析,不要重新發明輪子。僅供參考,'int'還允許任意的前導和尾隨空格; 'int('-2')'完全合法,但會失敗'isdigit'測試。 – ShadowRanger

3

總是有try/except

oldlist = ['A', '2', '8', 'B', '3'] 
newlist = [] 
for x in oldlist: 
    try: 
     newlist.append(int(x)) 
    except ValueError: 
     newlist.append(x) 

newlist 
# ['A', 2, 8, 'B', 3] 
1

我只想提取轉化成功能。

def int_if_possible(value): 
    try: 
     return int(value) 
    except (ValueError, TypeError): 
     return value 

int_list = [int_if_possible(i) for i in int_list] 

此外,我將您的列表重命名爲int_list,以便我們仍然可以使用列表構造函數(如果需要)。

+0

爲了概括起來,你可能想要做'except(ValueError,TypeError):',所以你不要在不能成爲'int'的類型上(例如'list','tuple'等等)。如果'list'全部是'str','ValueError'就沒問題,但如果它是混合類型的,並且只想轉換類似int的'str'而不改變其他東西,那麼處理TypeError會讓你感覺到。 – ShadowRanger

+0

聽起來很公平。該問題僅提及整數或字符串,因此實施者應該知道哪一個是合適的。我已經更新了我的答案,因爲它使得該功能在這種情況下更加靈活。 – Shadow

0

您可以使用嘗試,除塊

lst1 = ['A', '2', '8', 'B', '3'] 
lst2 = [] 
for i in lst1: 
    try: 
     lst2.append(int(i)) 
    except ValueError: 
     lst2.append(i) 

print lst2