V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
kmdd33
V2EX  ›  Python

这段 Python 代码中,解释器如何能理解到 i 代表的是 h 中的各个元素呢?一开始也没有定义啊?

  •  
  •   kmdd33 · 2018-08-21 13:11:49 +08:00 · 2160 次点击
    这是一个创建于 2068 天前的主题,其中的信息可能已经有所发展或是发生改变。

    def heapsort(iterable):

     h = []
    
     for value in iterable:
    
      heappush(h, value)
    
     return [heappop(h) for i in range(len(h))]
    

    heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    9 条回复    2018-08-24 01:01:18 +08:00
    ArianX
        1
    ArianX  
       2018-08-21 13:46:07 +08:00 via Android
    和 i 无关,因为用的是堆排序
    huangzhe8263
        2
    huangzhe8263  
       2018-08-21 13:49:53 +08:00 via Android
    列表生成式+range ? ,i 就是 index 吧
    Hstar
        3
    Hstar  
       2018-08-21 13:56:35 +08:00
    因为 i 并不代表 h 中的各个元素。。能排序是因为 heapop 方法自动取出 h 中最小值
    vimiix
        4
    vimiix  
       2018-08-21 14:03:54 +08:00
    可以把 `i ` 替换为 `_` ,这里只是做迭代用
    leoleoasd
        5
    leoleoasd  
       2018-08-21 14:13:14 +08:00
    i 是 0-len(h)的数字 并不是元素
    有挂这个你可以看一看堆的性质
    只是简单的执行了 len(h)次 pop 而已
    pop 的意思就是弹出堆中最小的元素
    MicroCatPad
        6
    MicroCatPad  
       2018-08-21 15:17:03 +08:00
    你改成 [heappop(h) for _ in range(len(h))] 也一样
    Marsss
        7
    Marsss  
       2018-08-21 15:44:03 +08:00
    为什么我觉得完全不困惑。。。range(len(xxx)) 这就决定了数据类型啊。
    wonderay
        8
    wonderay  
       2018-08-22 09:42:24 +08:00
    感觉各位都答偏了
    i 并不代表 h 中的各个元素, 而是代表 从 0 到 len(h) - 1 的每个数字,其实是为了限定 heappop 的调用次数
    Gordongg
        9
    Gordongg  
       2018-08-24 01:01:18 +08:00 via Android
    这里的 for i in range(len(h)) 和 for _ in range(len(h)) 作用一样 都是循环 h 次的意思
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5359 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 08:56 · PVG 16:56 · LAX 01:56 · JFK 04:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.