如何迭代字母和数字

时间:2012-03-17 06:17:32

标签: python numbers loops itertools letters

我想知道如何在Python中迭代一系列条件。

  1. 具有2-6个较低字母或数字字符的字符串
  2. 第一个字符始终是数字
  3. 所以短暂的进展将是:

    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 个答案:

答案 0 :(得分:5)

您可以使用itertools.productitertools.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)]

答案 1 :(得分: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.

答案 2 :(得分: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

答案 3 :(得分:-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)

我认为这比我之前想要展示的更有意义。 :) 如果你不明白这个想法,请告诉我..顺便说一句,这是一个有趣的问题:)