创建具有固定数量元素(长度)的范围 [英] Creating a range with fixed number of elements (length)

查看:24
本文介绍了创建具有固定数量元素(长度)的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python 2.7, how can I create a list over a range with a fixed number of elements, rather than a fixed step between each element?

>>> # 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.

I use numpy for this.

>>> 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]

这篇关于创建具有固定数量元素(长度)的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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