Python range function

荒凉一梦 提交于 2021-02-06 09:54:09

问题


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?


回答1:


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)



回答2:


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

numpy.arange(0, 100, 0.5)

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



回答3:


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)]:




回答4:


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




回答5:


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



回答6:


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



来源:https://stackoverflow.com/questions/7531945/python-range-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!