Python 如何创建具有给定增量的数字范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18325312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a range of numbers with a given increment
提问by Vaidyanathan
I want to know whether there is an equivalent statement in lists to do the following. In MATLAB I would do the following
我想知道列表中是否有一个等效的语句来执行以下操作。在 MATLAB 中,我会执行以下操作
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);
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中的列表)并打印到一个文件。
采纳答案by lmjohns3
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
:
在 Python 中,range(start, stop + 1, step)
可以像 Matlab 的start:step:stop
命令一样使用。与Matlab的功能,但是,range
只能当start
,step
和stop
都是整数。如果您想要一个处理浮点值的并行函数,请尝试以下arange
命令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))
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 tothe stop value.
请记住,不同于MATLAB,range
并且np.arange
都希望他们的论点的顺序start
,stop
话step
。还要记住的是,不同于Matlab的语法,range
并且np.arange
都停止只要电流值大于或等于停止值。
http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html
http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html
回答by mshsayem
open('inc.txt','w').write("\n".join(str(i) for i in range(init,final,inc)))
回答by Peter Varo
You can easily create a function for this. The first three arguments of the function will be the range parameters as integers and the last, fourth argument will be the filename, as a string:
您可以轻松地为此创建一个函数。该函数的前三个参数将是整数形式的范围参数,最后一个第四个参数将是文件名,作为字符串:
def range_to_file(init, final, inc, fname):
with open(fname, 'w') as f:
f.write('\n'.join(str(i) for i in range(init, final, inc)))
Now you have to call it, with your custom values:
现在您必须使用自定义值调用它:
range_to_file(1, 51, 5, 'inc.txt')
So your output will be (in the fname
file):
所以你的输出将是(在fname
文件中):
1
6
11
16
21
26
31
36
41
46
NOTE:in Python 2.x a
range()
returns a list, in Python 3.x arange()
returns an immutable sequence iterator, and if you want to get a list you have to writelist(range())
注意:在 Python 2.xa 中
range()
返回一个列表,在 Python 3.xa 中range()
返回一个不可变序列迭代器,如果你想得到一个列表,你必须写list(range())
回答by Madison May
I think your looking for something like this:
我认为你在寻找这样的东西:
nums = range(10) #or any list, i.e. [0, 1, 2, 3...]
number_string = ''.join([str(x) for x in nums])
The [str(x) for x in nums]
syntax is called a list comprehension. It allows you to build a list on the fly. '\n'.join(list)
serves to take a list of strings and concatenate them together. str(x)
is a type cast: it converts an integer to a string.
该[str(x) for x in nums]
语法称为列表推导式。它允许您即时构建列表。 '\n'.join(list)
用于获取字符串列表并将它们连接在一起。str(x)
是类型转换:它将整数转换为字符串。
Alternatively, with a simple for loop:
或者,使用一个简单的 for 循环:
number_string = ''
for num in nums:
number_string += str(num)
The key is that you cast the value to a string before concatenation.
关键是在连接之前将值转换为字符串。
回答by iamauser
test.py
contains :
test.py
包含:
#!/bin/env python
f = open("test.txt","wb")
for i in range(1,50,5):
f.write("%d\n"%i)
f.close()
You can execute
你可以执行
python test.py
蟒蛇测试.py
file test.txt
would look like this :
文件test.txt
看起来像这样:
1
6
11
16
21
26
31
36
41
46
回答by dslack
I think that the original poster wanted 51 to show up in the list, as well.
我认为原始海报也希望 51 出现在列表中。
The Python syntax for this is a little awkward, because you need to provide for range (or xrange or arange) an upper-limit argument that is one increment beyond your actual desired upper limit. An easy solution is the following:
用于此的 Python 语法有点笨拙,因为您需要为 range(或 xrange 或 arange)提供一个上限参数,该参数是超出您实际所需上限的一个增量。一个简单的解决方案如下:
init = 1
final = 51
inc = 5
with open('inc.txt','w') as myfile:
for nn in xrange(init, final+inc, inc):
myfile.write('%d\n'%nn)