Is there a built-in Python function to generate 100 numbers from 0 to 1?

天大地大妈咪最大 提交于 2019-12-13 02:58:44

问题


I am looking for something like range, but one that will allow me to specify the start and the end value, along with how many numbers I need in the collection which I want to use in a similar fashion range is used in for loops.


回答1:


No, there is no built-in function to do what you want. But, you can always define your own range:

def my_range(start, end, how_many):
    incr = float(end - start)/how_many
    return [start + i*incr for i in range(how_many)]

And you can using in a for-loop in the same way you would use range:

>>> for i in my_range(0, 1, 10):
...     print i
... 
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

EDIT: If you want both start and end to be part of the result, your my_range function would be:

def my_range(start, end, how_many):
    incr = float(end - start)/(how_many - 1)
    return [start + i*incr for i in range(how_many-1)] + [end]

And in your for-loop:

>>> for i in my_range(0, 1, 10):
...   print i
... 
0.0
0.111111111111
0.222222222222
0.333333333333
0.444444444444
0.555555555556
0.666666666667
0.777777777778
0.888888888889
1



回答2:


Python doesn't have a floating point range function but you can simulate one easily with a list comprehension:

>>> lo = 2.0
>>> hi = 12.0
>>> n = 20
>>> [(hi - lo) / n * i + lo for i in range(n)]
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5]

Note, in numeric applications, people typically want to include both endpoints rather than have a half-open interval like Python's built-in range() function. If you need both end-points you can easily add that by changing range(n) to range(n+1).

Also, consider using numpy which has tools like arange() and linspace() already built in.




回答3:


You can still use range, you know. You just need to start out big, then divide:

for x in range(100):
    print x/100.0

If you want to include the endpoint:

for x in range(101):
    print x/100.0



回答4:


There is a special function in numpy to do this: linspace. Ofcourse you will have to install numpy first. You can find more about it here.



来源:https://stackoverflow.com/questions/8652006/is-there-a-built-in-python-function-to-generate-100-numbers-from-0-to-1

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