5

Python で一連の条件を反復処理する方法を知りたいです。

  1. 2 ~ 6 個の小文字の英字または数字を含む文字列
  2. 最初の文字は常に数字です

したがって、短い進行は次のようになります。

1a
1b
1c
...
1aa
1ab
1ac
...
2aaa
2aab
2aac

etc.

最初の 2 つを実行できる恐ろしい例は次のとおりです。

##Loop through 1a-z0-9
start = '1'
l = 97
while l < 123:
    num = start
    num += chr(l)
    print num
    l += 1

l = 48
while l < 58:
    num = start
    num += chr(l)
    print num
    l += 1

itertools を見つけましたが、良い例が見つかりません。

4

4 に答える 4

5

itertools.productと を使用してこれを行うことができますitertools.chain。最初に数字と文字の文字列を定義します。

numbers = '0123456789'
alnum = numbers + 'abcdefghijklmnopqrstuvwxyz'

を使用itertools.productすると、さまざまな長さの文字列の文字を含むタプルを取得できます。

len2 = itertools.product(numbers, alnum) # length 2
len3 = itertools.product(numbers, alnum, alnum) # length 3
...

すべての長さのイテレータを連鎖させ、タプルを文字列に結合します。私はリスト内包表記でそれを行います:

[''.join(p) for p in itertools.chain(len2, len3, len4, len5, len6)]
于 2012-03-17T07:49:29.727 に答える
3

I would go with product function from itertools.

import itertools 
digits = '0123456789'
alphanum = 'abcdef...z' + digits # this should contain all the letters and digits

for i in xrange(1, 6):    
    for tok in itertools.product(digits, itertools.product(alphanum, repeat=i)):
        # do whatever you want with this token `tok` here.
于 2012-03-17T07:34:16.743 に答える
1

この問題は、基数 26 で考えることができます (最初の数字を無視して、これを別のケースに入れます。) したがって、基数 26 で 'a' から 'zzzzzz' までの範囲の文字を使用すると、0 と ( 26,26,26,26,26) = 26 ^ 0 + 26 + 26^2 + 26^3 + 26^4 + 26^5. これで、数字から文字への全単射が得られました。数字から単語に変換する関数を書きたいだけです。

 letters = 'abcdef..z'

 def num_to_word( num ):
      res = ''
      while num:
           res += letters[num%26]
           num //= 26
      return res

これを列挙する関数を書きます

 def generator():
     for num in xrange(10):
         for letter_num in xrange( sum( 26 ** i for i in xrange( 6 ) ) + 1 ):
             tok = str(num) + num_to_word( letter_num )
             yield tok
于 2012-03-17T07:48:32.520 に答える
-1

幅優先検索タイプのアルゴリズムでこれを行うことができます

starting from 
Root:
    have 10 children, i = 0,1,...,9
    so , this root must have an iterator, 'i'
    therefore this outermost loop will iterate 'i' from 0 to 9

i:
    for each 'i', there are 5 children (ix , ixx, ixxx, ixxxx, ixxxxx)
    ( number of chars at the string )
    so each i should have its own iterator 'j' representing number of chars
    the loop inside Root's loop will iterate 'j' from 1 to 5

j:
    'j' will have 'j' number of children ( 1 -> x , 2 -> xx ,..., 5-> xxxxx)
    so each j will have its own iterator 'k' representing each "character"
    so, 'k' will be iterated inside this j loop, from 1 to j
    ( i=2, j=4, k = 3 will focus on 'A' at string  "2xxAx" )

k:
    each 'k' represents a character, so it iterates from 'a' to 'z'
    each k should have a iterator(value) 'c' that iterates from 'a' to 'z' (or 97 to 122)

これは、私が以前に示したかったことよりも理にかなっていると思います。:) わからない場合は教えてください..ところで、それは興味深い質問です:)

于 2012-03-17T06:22:35.630 に答える