python - 创建具有固定数量元素(长度)的范围

标签 python python-2.7 floating-point range

在 Python 2.7 中,如何创建一个范围内具有固定数量元素的列表,而不是每个元素之间的固定步长?

>>> # Creating a range with a fixed step between elements is easy:
>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
>>> # I'm looking for something like this:
>>> foo(0, 10, num_of_elements=4)
[0.0, 2.5, 5, 7.5]

最佳答案

我为此使用了 numpy。

>>> import numpy as np
>>> np.linspace(start=0, stop=7.5, num=4)
array([ 0. ,  2.5,  5. ,  7.5])
>>> list(_)
[0.0, 2.5, 5.0, 7.5]

关于python - 创建具有固定数量元素(长度)的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27043915/

相关文章:

python - 如果数字能整除,则将商设为整数

Python turtle 在边界内随机游走

Python:Networkx获取给定两个节点之间具有节点和边的路径

c - 为什么带有 float 的 x 和 y 总是 0?

Python 减去 float

python - np.exp() 的数值问题

python - 在 centos 5 上安装 Tensorflow

python - 客户端脚本在UDP套接字上停止时获取ConnectionResetError

python - 即使已安装,“导入 future ”也不起作用

python - 我如何添加try/(如果性别拼写错误的情况除外)?