2011-03-24 153 views
0

我想使用python re模块按数字数字过滤int数字。如何使用python re模块按数字过滤int数字

1 
    700 
76093 
71365 
35837 
75671 
^^     
||--------------------- this position should not be 6,7,8,9,0 
|---------------------- this position should not be 5,6,7 

代码:

int_list=[1,700,76093,71365,35837,75671] 
str_list = [str(x).zfill(5) for x in int_list] 
reexp = r"\d[0-4,8-9][1-5]\d\d" 
import re 
p = re.compile(reexp) 
result = [int("".join(str(y) for y in x)) for x in str_list if p.match(x)] 

我有2个问题:

1.Is可以生成从下面的代码串reexp:

thousand_position = set([1,2,3,4,5,1,1,1,1,1,1,1,1,1,1]) 
hundred_position = set([1,2,3,4,8,9,0,1,2,3,2,3,1,2]) 

2.how到使reexp更简单,避免低于0的前缀错误?

00700 
00500   <--- this will also drops into the reexp, it is a 
        bug because it has no kilo number 
10700 

reexp = r"\d[0-4,8-9][1-5]\d\d" 

感谢您的时间

B.Rgs

PS:感谢suggstion下面的数学解决方案,我知道这可能是容易和更快,但我想基于RE版到平衡其他想法。

+0

just fyi,see my edited answer。让我知道它是否有任何问题。 – senderle 2011-03-25 00:12:47

回答

1

好吧,首先,我要发布一些代码,实际上做你的描述开始:

>>> int_list=[1, 700, 76093, 71365, 35837, 75671] 
>>> str_list = [str(i).zfill(5) for i in int_list] 
>>> filtered = [s for s in str_list if re.match('\d[0-4,8-9][1-5]\d\d', s)] 
>>> filtered 
['71365'] 

编辑:好吧,我想我现在明白你的问题。您可以使用rjust,而不是使用zfill,它将插入空格而不是零。

>>> int_list=[1,700,76093,71365,35837,75671,500] 
>>> str_list = [str(i).rjust(5) for i in int_list] 
>>> re_str = '\d' + str(list(set([0, 1, 3, 4, 8, 9]))) + str(list(set([1, 2, 3, 4, 5]))) + '\d\d' 
>>> filtered = [s for s in str_list if re.match(re_str, s)] 
>>> filtered 
['71365'] 

我认为这样做数学,因为颜建议最后会更快,但也许你有你的理由使用正则表达式。

+0

感谢您的回答,第二个问题在这里工作,因为00700没有在正则表达式'\ d [0-4,8-​​9] [1-5] \ d \ d'中下降,但00500怎么样? – user478514 2011-03-24 05:15:26

+0

@ user478514:我修改了第二个版本来做我认为你想要的东西。 – senderle 2011-03-24 13:29:03

4

您确定要使用re模块吗?你可以通过一些简单的数学操作来了解你想要做什么。

def valid_number(n): 
    return 0 < n%1000/100 < 6 and not 5 >= n%10000/1000 >= 7 

int_list = [1,700,76093,71365,35837,75671,] 
result = [x for x in int_list if valid_number(x)] 

或者:

result = filter(valid_number, int_list) 
+0

感谢您的快速纯数学解决方案,但我想用重新使这些非数学家的问题更简单,通过使用重新和数字我可以添加用户界面0-9复选框后,也许.. 。我可以知道这里n%是什么意思吗? – user478514 2011-03-24 04:41:33