是否有内置的Python函数可以生成0到1之间的100个数字? [英] Is there a built-in Python function to generate 100 numbers from 0 to 1?
问题描述
我正在寻找类似range
的东西,但是它将允许我指定起始值和结束值,以及我想要以类似方式使用的集合中需要多少个数字range
在for loops
中使用.
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
.
推荐答案
不,没有内置函数可以执行您想要的操作.但是,您始终可以定义自己的range
:
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)]
并且您可以使用与range
相同的方式在for循环中使用:
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
编辑:如果您希望start
和end
都作为结果的一部分,则my_range
函数将是:
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]
在您的for循环中:
>>> 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
这篇关于是否有内置的Python函数可以生成0到1之间的100个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!