提取数组的特定部分

时间:2014-08-05 15:54:01

标签: python string list

我有以下列表

array = [CHR.calc.2850_00145,CHR.calc.2860_045140,CHR.calc.2870_015,CHR.calc.2880_0160]

我想拥有以下输出列表:

  array = [ 2850,2860,2870,2880]

问候,

3 个答案:

答案 0 :(得分:3)

>>> array = [
...     'CHR.calc.2850_00145',
...     'CHR.calc.2860_045140',
...     'CHR.calc.2870_015',
...     'CHR.calc.2880_0160',
... ]
>>> [x.split('.')[2].split('_')[0] for x in array]
['2850', '2860', '2870', '2880']
>>> [int(x.split('.')[2].split('_')[0]) for x in array]
[2850, 2860, 2870, 2880]

答案 1 :(得分:2)

arr = [int(s[9:13]) for s in array]
# assuming the contents of array are strings all of the same format.

答案 2 :(得分:0)

这可能不是一个简单的解决方案,但非常有效

import re

pattern = re.compile("(\d.*)_")

result = []
array = ['CHR.calc.2850_00145',
       'CHR.calc.2860_045140',
       'CHR.calc.2870_015',
       'CHR.calc.2880_0160']

for word in array:
    result.append(re.findall(pattern, word)[0])

['2850', '2860', '2870', '2880']