一、解析思路
1.生成0-9:
x = [str(x) for x in range(0, 10)]
print(x)
结果
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
2.生成a-z:
y = [chr(y) for y in range(97, 123)]
print(y)
结果
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
3.生成0-z:
x = [str(x) for x in range(0, 10)]
y = [chr(y) for y in range(97, 123)]
print(x+y)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
4.itertools之product函数:
product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.
即: product(A, B) 和 ((x,y) for x in A for y in B)的效果一样
使用形式如下:itertools.product(*iterables, repeat=1)
iterables 是可迭代对象, repeat指定 iterable 重复几次
即: itertools.product(A,repeat=3)等价于itertools.product(A,A,A)
import itertools
A = [1, 2, 3]
for i in itertools.product(A, repeat=3):
print(i)
结果
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)
(1, 3, 1)
(1, 3, 2)
(1, 3, 3)
(2, 1, 1)
(2, 1, 2)
(2, 1, 3)
(2, 2, 1)
(2, 2, 2)
(2, 2, 3)
(2, 3, 1)
(2, 3, 2)
(2, 3, 3)
(3, 1, 1)
(3, 1, 2)
(3, 1, 3)
(3, 2, 1)
(3, 2, 2)
(3, 2, 3)
(3, 3, 1)
(3, 3, 2)
(3, 3, 3)
5.join()方法
join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串
语法:str.join(sequence)
参数:sequence – 要连接的元素序列,
返回结果:通过指定字符连接序列中元素后生成的新字符串
示例:
str = "-"
seq = ("a", "b", "c") # 字符串序列
print (str.join(seq))
print (''.join(seq))
执行结果:
a-b-c
abc
二、循环遍历0-9,a-z,代码如下:
import itertools
x = [str(x) for x in range(0, 10)]
y = [chr(y) for y in range(97, 123)]
date = x+y
for i in range(1, 4):
for j in itertools.product(date, repeat=i):
print(''.join(j))
#break
执行结果如下(部分示例):
10
11
12
13
14
15
16
17
18
19
1a
1b
1c
1d
1e
1f
1g
1h
1i
1j
1k
1l
1m
1n
1o
1p
1q
1r
1s
1t
1u
1v
1w
1x
1y
1z
20
21
22
23
24
25
26
27
28
29
2a
2b
2c
2d
2e
2f
2g
2h
2i
2j
2k
2l
2m
2n
2o
2p
2q
2r
2s
2t
2u
2v
2w
2x
2y
2z