开发者

Python range function

开发者 https://www.devze.com 2023-04-07 06:01 出处:网络
Say I want to loop from 0 to 100 but with a step of 1/2.If you 开发者_运维知识库try for i in range(0, 100, 0.5):

Say I want to loop from 0 to 100 but with a step of 1/2. If you 开发者_运维知识库try

for i in range(0, 100, 0.5):
    whatever

Error:

the step must not be 0

Question: Is there any built-in way in Python 2.x to do something like this?


Python2.x:

for idx in range(0, int(100 / 0.5)):

    print 0.5 * idx      

outputs:

0.0

0.5

1.0

1.5

..

99.0

99.5


Numpy:

numpy.arange would also do the trick.

numpy.arange(0, 100, 0.5)


If you have numpy, here are two ways to do it:

numpy.arange(0, 100, 0.5)

numpy.linspace(0, 100, 200, endpoint=False)


You have to use integer steps for range() and xrange(). That's why your 0.5 step gets internally converted to 0 and you get that error. Try for i in [j / 2.0 for j in xrange(100 * 2)]:


You'll have to either create the loop manually, or define your own custom range function. The built-in requires an integer step value.


for x in map(lambda i: i * 0.5, range(0,200)):
  #Do something with x


For large ranges it is better to use an generator expression than building a list explicitly:

 for k in ( i*0.5 for i in range(200) ):
     print k

This consumes not much extra memory, is fast und easy to read. See http://docs.python.org/tutorial/classes.html#generator-expressions

0

精彩评论

暂无评论...
验证码 换一张
取 消