您是否应该始终偏爱xrange()而不是range()? [英] Should you always favor xrange() over range()?

查看:95
本文介绍了您是否应该始终偏爱xrange()而不是range()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么或为什么不呢?

推荐答案

为了提高性能,尤其是在较大范围内进行迭代时,xrange()通常更好.但是,在某些情况下,您可能更喜欢range():

For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range():

  • 在python 3中,range()会执行xrange()曾经做过的事情,而xrange()不存在.如果要编写可同时在Python 2和Python 3上运行的代码,则不能使用xrange().

  • In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange().

range()可能会更快-例如.如果多次重复相同的序列. xrange()每次都必须重建整数对象,但是range()将具有真实的整数对象. (但是,在内存方面,它总是会表现得更差)

range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)

xrange()在需要真实列表的所有情况下都不可用.例如,它不支持切片或任何列表方法.

xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.

有几篇文章提到2to3工具将如何升级range().作为记录,这是在range()xrange()

There are a couple of posts mentioning how range() will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range() and xrange()

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@

 for x in range(20):
-    a=range(20)
+    a=list(range(20))
     b=list(range(20))
     c=[x for x in range(20)]
     d=(x for x in range(20))
-    e=xrange(20)
+    e=range(20)

如您所见,在for循环或理解中使用时,或已经用list()包装的地方,范围保持不变.

As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.

这篇关于您是否应该始终偏爱xrange()而不是range()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆