python - range() 和 xrange() 该选择哪个呢?
ringa_lee
ringa_lee 2017-04-17 13:36:06
0
8
769

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

ringa_lee
ringa_lee

ringa_lee

reply all(8)
巴扎黑

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:

PHPzhong

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~~

黄舟

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.

左手右手慢动作

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

洪涛

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

阿神

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.

大家讲道理

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

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!