python1到100,是否有内置的Python函数可以生成0到1之间的100个数字?

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值