5

我想知道如何在 Python 中遍历一组条件。

  1. 具有 2-6 个小写字母或数字字符的字符串
  2. 第一个字符始终是数字

所以一个简短的进展将是:

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

etc.

可以做到前两个的一个可怕的例子是

##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

我会使用 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' 到 'zzzzz' 的字母将是 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 回答