我想知道如何在Python中迭代一组条件。
。
因此,一个简短的进展是:
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
我找到了迭代工具,但是找不到好的例子。
发布于 2012-03-17 07:49:29
您可以使用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-17 07:34:16
我会使用迭代工具中的产品函数。
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-17 07:48:32
您可以在基数26中考虑这个问题(忽略第一个数字,我们将把它放在一个单独的例子中)。因此,对于基数26中从“a”到“zzzzz”的字母是0和( 26,26,26,26)=26^0+ 26^2 +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
https://stackoverflow.com/questions/9747779
复制相似问题