range()不是检查范围的最佳方法吗? [英] range() is not the best way to check range?

查看:55
本文介绍了range()不是检查范围的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎range()可能非常慢:


以下程序将运行,最后一行显示它运行了多长时间

for :


导入时间


startTime = time.time()


a = 1.0

for i in range(0,30000):

if i in range(0,10000):

a + = 1

如果不是我%1000:打印我


打印一个, ",round(time.time() - startTime,1)," seconds"

---------------------- -----------

最后一行输出是

----------------- ----------------


10001.0 22.8秒


所以,如果我换行


如果我在范围内(0,10000):





如果我> = 0且i < 10000:


最后一行是


10001.0 0.2秒


如此近,程序的运行速度提高了100倍!


或是否有另外一种使用range()或类似的东西可以和b $ b一样快?

解决方案

Su *** *********@gmail.com 写道:


似乎range()可能非常慢:



....


if i in range(0,10000):



这将创建一个10,000个元素的列表并按顺序搜索它。

当然会慢一点。


Su ************ @ gmail.com 写道:


或者是否有替代使用范围()或类似的东西可以和b $ b一样快?



你可以使用xrange:


leif @ ubuntu:〜


python -m timeit -n10000" 1 in range(10000)"

10000循环,最佳3:260 usec每循环

leif @ ubuntu:〜

it seems that range() can be really slow:

the following program will run, and the last line shows how long it ran
for:

import time

startTime = time.time()

a = 1.0
for i in range(0, 30000):
if i in range (0, 10000):
a += 1
if not i % 1000: print i

print a, " ", round(time.time() - startTime, 1), "seconds"
---------------------------------
the last line of output is
---------------------------------

10001.0 22.8 seconds

so if i change the line

if i in range (0, 10000):

to

if i >= 0 and i < 10000:

the the last line is

10001.0 0.2 seconds

so approximately, the program ran 100 times faster!

or is there an alternative use of range() or something similar that can
be as fast?

解决方案

Su************@gmail.com wrote:

it seems that range() can be really slow:

....

if i in range (0, 10000):

This creates a 10,000-element list and sequentially searches it. Of
course that''s gonna be slow.


Su************@gmail.com wrote:

or is there an alternative use of range() or something similar that can
be as fast?

You could use xrange:

leif@ubuntu:~


python -m timeit -n10000 "1 in range(10000)"
10000 loops, best of 3: 260 usec per loop
leif@ubuntu:~


这篇关于range()不是检查范围的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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