如何创建具有给定增量的数字范围 [英] How to create a range of numbers with a given increment
问题描述
我想知道列表中是否存在等效语句以执行以下操作.在MATLAB中,我将执行以下操作
I want to know whether there is an equivalent statement in lists to do the following. In MATLAB I would do the following
fid = fopen('inc.txt','w')
init =1;inc = 5; final=51;
a = init:inc:final
l = length(a)
for i = 1:l
fprintf(fid,'%d\n',a(i));
end
fclose(fid);
简而言之,我有一个初始值,一个最终值和一个增量.我需要创建一个数组(我读到的内容等同于python中的列表)并打印到文件中.
In short I have an initial value, a final value and an increment. I need to create an array (I read it is equivalent to lists in python) and print to a file.
推荐答案
在Python中,可以像Matlab的start:step:stop
命令一样使用range(start, stop + 1, step)
.但是,与Matlab的功能不同,range
仅在start
,step
和stop
都是整数时才起作用.如果要使用可用于浮点值的并行函数,请尝试使用numpy
中的arange
命令:
In Python, range(start, stop + 1, step)
can be used like Matlab's start:step:stop
command. Unlike Matlab's functionality, however, range
only works when start
, step
, and stop
are all integers. If you want a parallel function that works with floating-point values, try the arange
command from numpy
:
import numpy as np
with open('numbers.txt', 'w') as handle:
for n in np.arange(1, 5, 0.1):
handle.write('{}\n'.format(n))
请记住,与Matlab不同,range
和np.arange
都期望其参数依次为start
,stop
,然后是step
.还请记住,与Matlab语法不同,range
和np.arange
都会在当前值大于或等于终止值时立即停止.
Keep in mind that, unlike Matlab, range
and np.arange
both expect their arguments in the order start
, stop
, then step
. Also keep in mind that, unlike the Matlab syntax, range
and np.arange
both stop as soon as the current value is greater than or equal to the stop value.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html
这篇关于如何创建具有给定增量的数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!