2016-07-15 75 views
-1

我有與上述列表:如何字符串轉換成整數的python sickit學習

probs= ['2','3','5','6'] 

,我想這些字符串轉換爲數值類似下面的結果:

resultat=[2, 3, 4, 5, 6] 

我試過出現此鏈接一些解決方案: How to convert strings into integers in Python? 像這樣的:

new_list = list(list(int(a) for a in b) for b in probs if a.isdigit()) 

但它沒有工作,有人可以幫助我適應這個功能在我的數據結構上,我會非常感激。

+0

'resultat = [INT(項目)的項目在probs]'? – mgilson

+0

只是語法問題。您正在創建一個列表清單。相反,使用: 'new_list = list(int(a)for a probs if a.isdigit())' – user1952500

回答

0
>>> probs= ['2','3','5','6'] 
>>> probs= map(int, probs) 
>>> probs 
[2, 3, 5, 6] 

或(如註釋):

>>> probs= ['2','3','5','6'] 
>>> probs = [int(e) for e in probs] 
>>> probs 
[2, 3, 5, 6] 
>>> 
+0

謝謝@Billal的答案。但我收到以下錯誤: ValueError:int()以10爲底的無效文字:'0.00390625' –

+1

它必須更改float()上的int(),它的工作非常好。我很感謝 –

3

使用int()和列表理解迭代列表並將字符串值轉換爲整數。

>>> probs= ['2','3','5','6'] 
>>> num_probs = [int(x) for x in probs if x.isdigit()] 
>>> num_probs 
[2, 3, 5, 6] 
2

如果您的列表如上,你並不需要檢查,如果值是一個數字。 像

probs = ["3","4","4"]; 
resultat = []; 

for x in probs: 
    resultat.append(int(x)) 

print resultat 

會工作

+0

謝謝@ Idco0的答案。但我收到以下錯誤: 文件「stdin」,lin 2 resultat.append(int(x)) IdentationError:預期一個縮進塊 –

相關問題