是否有内置的Python函数可以生成0到1之间的100个数字? [英] Is there a built-in Python function to generate 100 numbers from 0 to 1?

查看:1468
本文介绍了是否有内置的Python函数可以生成0到1之间的100个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似range的东西,但是它将允许我指定起始值和结束值,以及我想要以类似方式使用的集合中需要多少个数字rangefor 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

编辑:如果您希望startend都作为结果的一部分,则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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆