0

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.以下のコードから再表現文字列を生成することは可能ですか:

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.再式をより単純にする方法は、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:以下の数学ソリューションの提案に感謝します。簡単で高速な場合があることはわかっていますが、reベースのバージョンで他の考えのバランスを取りたいです。

4

2 に答える 2

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)
于 2011-03-24T04:26:28.090 に答える
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']

編集:わかりました、私は今あなたの質問を理解していると思います。を使用する代わりに、ゼロの代わりにスペースを挿入する をzfill使用できます。rjust

>>> 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']

ヤンが示唆するようにこれを数学的に行うと、最終的には高速になると思いますが、正規表現を使用する理由があるかもしれません。

于 2011-03-24T05:06:03.843 に答える