zoukankan      html  css  js  c++  java
  • 【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)+'
    ')
    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+'
    ')
    f.close()
    t2 = time.time()
    print(t2-t1)
    # 80.10285377502441
    

    对比

    总计用时

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

    代码风格

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

    结果

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

  • 相关阅读:
    0808 HTML 基础
    2016.8.3 C#基础 结构体,枚举类型
    2016.8.1 C#基础 传值
    2016.7.22
    2016.7.20
    2016.7.31C#基础 函数
    2016.07.30C#基础 特殊集合
    2016.7.28C#基础 集合
    个人项目网页3
    个人项目网页2
  • 原文地址:https://www.cnblogs.com/ghgxj/p/14219070.html
Copyright © 2011-2022 走看看