How to use a decimal range() step value?

前端 未结 30 2635
醉话见心
醉话见心 2020-11-21 22:34

Is there a way to step between 0 and 1 by 0.1?

I thought I could do it like the following, but it failed:

for i in range(0, 1, 0.1):
    print i
         


        
30条回答
  •  萌比男神i
    2020-11-21 23:04

    [x * 0.1 for x in range(0, 10)] 
    

    in Python 2.7x gives you the result of:

    [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

    but if you use:

    [ round(x * 0.1, 1) for x in range(0, 10)]
    

    gives you the desired:

    [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

提交回复
热议问题