Python range function

后端 未结 6 950
广开言路
广开言路 2021-02-07 05:53

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


        
相关标签:
6条回答
  • 2021-02-07 06:25

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

    0 讨论(0)
  • 2021-02-07 06:33
    for x in map(lambda i: i * 0.5, range(0,200)):
      #Do something with x
    
    0 讨论(0)
  • 2021-02-07 06:34

    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 讨论(0)
  • 2021-02-07 06:38

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

    0 讨论(0)
  • 2021-02-07 06:40

    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)
    
    0 讨论(0)
  • 2021-02-07 06:43

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

    numpy.arange(0, 100, 0.5)
    
    numpy.linspace(0, 100, 200, endpoint=False)
    
    0 讨论(0)
提交回复
热议问题