2017-05-29 67 views
1

的陣列我有一個字符串'[1. 2. 3. 4. 5.]',我想轉換爲只得到INT這樣的,我獲得的[1, 2, 3, 4, 5]字符串到整數

整數數組我該怎麼辦呢?我嘗試使用map但未成功。

回答

2

使用strip測試remove []split爲皈依的valueslist其轉換爲intlist comprehension

s = '[1. 2. 3. 4. 5.]' 
print ([int(x.strip('.')) for x in s.strip('[]').split()]) 
[1, 2, 3, 4, 5] 

類似的解決方案與replace用於去除.

s = '[1. 2. 3. 4. 5.]' 
print ([int(x) for x in s.strip('[]').replace('.','').split()]) 
[1, 2, 3, 4, 5] 

或者與轉換先到float再到int

s = '[1. 2. 3. 4. 5.]' 
print ([int(float(x)) for x in s.strip('[]').split()]) 
[1, 2, 3, 4, 5] 

解決方案與map

s = '[1. 2. 3. 4. 5.]' 
#add list for python 3 
print (list(map(int, s.strip('[]').replace('.','').split()))) 
[1, 2, 3, 4, 5]