我有一个字符串'[1. 2. 3. 4. 5.]'
,我想转换为只获取int,以便获得[1, 2, 3, 4, 5]
的整数数组
我该怎么做?我尝试使用map
但不成功。
答案 0 :(得分:2)
使用strip
删除[]
,split
以转换为list
values
int
转换为list 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]
的解决方案:
RowSeparatorHeight