【问题标题】:Differences between using range() and xrange() in Python [duplicate]在 Python 中使用 range() 和 xrange() 之间的区别 [重复]
【发布时间】:2012-02-20 06:30:33
【问题描述】:

可能重复:
What is the difference between range and xrange?

目前我正在学习 Python。我发现使用 for 循环时有两种方法表示范围,即 range() 和 xrange()。谁能给我一些关于这两种方式之间的区别的想法,以及它们各自的合适场景是什么?谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    pydoc 在这些情况下是你的朋友!

    % pydoc range
    
    Help on built-in function range in module __builtin__:
    
    range(...)
        range([start,] stop[, step]) -> list of integers
    
        Return a list containing an arithmetic progression of integers.
        range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
        When step is given, it specifies the increment (or decrement).
        For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
        These are exactly the valid indices for a list of 4 elements.
    

    还有online here

    对比:

    % pydoc xrange
    
    Help on class xrange in module __builtin__:
    
    class xrange(object)
     |  xrange([start,] stop[, step]) -> xrange object
     |  
     |  Like range(), but instead of returning a list, returns an object that
     |  generates the numbers in the range on demand.  For looping, this is 
     |  slightly faster than range() and more memory efficient.
    

    还有online there!

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2018-02-18
      • 2021-03-21
      • 2010-09-10
      • 1970-01-01
      • 2016-12-28
      • 2010-10-17
      相关资源
      最近更新 更多