我想使用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