Skip to main content
 首页 » 编程设计

python之在 Python 中使用正则表达式识别数字列表

2024年10月24日41java哥

我正在处理来自在线数学辅导程序的数据,我希望能够识别这些问题的某些特征。例如,对于以下问题:

Find the median of the 7 numbers in the following list: 
[22, 13, 5, 16, 4, 12, 30] 

我想知道

1. the problem includes a list,  
2. how long the longest list in the problem is, and  
3. how many numbers are in the problem total.  

所以对于上面的问题,它有一个列表,列表有7个数字,总共有8个数字。

我已经编写了以下可以识别正数和负数以及 float 的正则表达式脚本,但我不知道如何识别列表中的一系列数字:

'[-+]{0,1}[0-9]+\.{0,1}(?! )[0-9]+' 

此外,数据格式不正确,以下所有示例都可能是数字列表的样子:

[1, 2, 3] 
1, 2, 3 
1,2,3. 
1,    2,    3,    4,    5 

我已经为此工作了几天,但一直无法取得任何进展。谁能帮忙?用正则表达式解决甚至可能不是问题,我只是不确定从这一点开始如何去做。

请您参考如下方法:

假设您将输入作为字符串 - 您可以使用 re.findall仅从中提取数字:

import re 
 
s = """[1, -2, 3] 
        1, 2, 3 
        1,2,3. 
        1,    2,    3,    4,    5""" 
 
res = re.findall(r'-?\d+', s) 
print res # ['1', '-2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '4', '5'] 
 
# and if you want to turn the strings into numbers: 
print map(int, res)  # [1, -2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5]