2017-05-29 66 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]