【python】迭代器与嵌套for循环生成密码字典速度对比

前言

分别使用迭代器嵌套for循环生成包含所有由数字组成的长度为8的密码字典,也就是从0000000099999999

代码

  • 迭代器
import time
t1 = time.time()
import itertools as its
iterator = its.product('0123456789', repeat=8)
f = open('pwd.txt', 'w')
for i in iterator:
    f.write(''.join(i)+'\n')
f.close()
t2 = time.time()
print(t2-t1)
# 62.58520317077637
  • 嵌套for循环
import time
t1 = time.time()
ls = '0123456789'
f = open('pwd.txt', 'w')
for i in ls:
    for j in ls:
        for k in ls:
            for x in ls:
                for y in ls:
                    for z in ls:
                        for m in ls:
                            for n in ls:
                                f.write(i+j+k+x+y+z+m+n+'\n')
f.close()
t2 = time.time()
print(t2-t1)
# 80.10285377502441

对比

总计用时

方法选择用时(单位:秒)
迭代器62.58520317077637
嵌套for循环80.10285377502441

代码风格

  • 迭代器:代码很短,风格良好。
  • 嵌套for循环:代码较长,且for循环的层层嵌套导致代码风格很差,不推荐。

结果

对比可见,用迭代器生成密码字典速度更快,且代码风格更加良好。

posted @ 2020-12-06 17:59  XavierJ  阅读(267)  评论(0编辑  收藏  举报