search

Home  >  Q&A  >  body text

python - range() 和 xrange() 该选择哪个呢?

这两个该如何选择,性能上、优缺点各自如何呢?

ringa_leeringa_lee2822 days ago794

reply all(8)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:38:06

    I accidentally saw this paragraph while reading "Python Learning Notes" by Q.yuhen. I wanted to add an answer to this question, so I cut the picture and turned it over:

    reply
    0
  • PHPz

    PHPz2017-04-17 13:38:06

    Everyone upstairs talks about the advantages of xrange, I will add the disadvantages
    1. python3 does not have xrange. If you migrate python2 to 3, or you want to run programs on 2/3 at the same time, you should pay attention.
    2. xrange does not support slicing, which may not be very enjoyable to use.

    Personally, if the amount of data is not large, you should still use range. If the data is large and it is version 2, consider using xrange.
    ps: Get to know both, and then choose the one that best suits your needs~~There is really no absolute~~

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:38:06

    range(start, end, step) will generate a list [start, start+step, start+2*step, ..., end]
    If the difference between start and end is large, it will take a long time to generate the list, and the amount of data will be large and occupy memory. After generation, iterate again.

    xrange(start, end, step) will not generate a list. It will generate one number at a time and will not affect memory.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:38:06

    Python 3 only has range, which has the same effect as Python 2’s xrange ~~

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:38:06

    Select range for normal programs, and use xrange for operations that may be time-consuming.

    reply
    0
  • 阿神

    阿神2017-04-17 13:38:06

    You can Google the implementation differences between range() and xrange().

    If the number in the range is not large, use range(); otherwise use xrange(). As for how big the number is, I will go with my feeling

    There is only range() in Python 3.x, but you know about Python version issues and maintenance issues.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:38:06

    Add that Python2’s xrange does not support slicing Python3’s range

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:38:06

    xrange finally returns a generator
    range is a list (python2.7)
    I personally like xrange a bit

    reply
    0
  • Cancelreply