我想使用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版到平衡其他想法。
just fyi,see my edited answer。让我知道它是否有任何问题。 – senderle 2011-03-25 00:12:47