Arrays 字符串到整数数组
我有一个字符串Arrays 字符串到整数数组,arrays,list,python-3.x,integer,Arrays,List,Python 3.x,Integer,我有一个字符串'[1.2.3.4.5.],我想转换为只获取int,这样我就获得了一个整数数组[1,2,3,4,5] 我该怎么做?我尝试使用map,但没有成功。使用strip删除[],使用拆分转换为列表理解中的值的列表: s = '[1. 2. 3. 4. 5.]' print ([int(x.strip('.')) for x in s.strip('[]').split()]) [1, 2, 3, 4, 5] 类似的解决方案是使用替换来删除: s = '[1. 2. 3. 4. 5.]' p
'[1.2.3.4.5.]
,我想转换为只获取int,这样我就获得了一个整数数组[1,2,3,4,5]
我该怎么做?我尝试使用
map
,但没有成功。使用strip
删除[]
,使用拆分
转换为列表理解中的值的列表
:
s = '[1. 2. 3. 4. 5.]'
print ([int(x.strip('.')) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
类似的解决方案是使用替换来删除
:
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]
使用映射的解决方案
:
s = '[1. 2. 3. 4. 5.]'
#add list for python 3
print (list(map(int, s.strip('[]').replace('.','').split())))
[1, 2, 3, 4, 5]
使用条带
删除[]
,拆分
转换为列表
中转换为int
的值
:
s = '[1. 2. 3. 4. 5.]'
print ([int(x.strip('.')) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
类似的解决方案是使用替换来删除
:
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]
使用映射的解决方案
:
s = '[1. 2. 3. 4. 5.]'
#add list for python 3
print (list(map(int, s.strip('[]').replace('.','').split())))
[1, 2, 3, 4, 5]