字符串到整数数组

时间:2017-05-29 13:05:17

标签: arrays list python-3.x integer

我有一个字符串'[1. 2. 3. 4. 5.]',我想转换为只获取int,以便获得[1, 2, 3, 4, 5]的整数数组

我该怎么做?我尝试使用map但不成功。

1 个答案:

答案 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