Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - How to create a range of numbers with a given increment

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
',a(i));
end
fclose(fid);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('{}
'.format(n))

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...