python - 如何创建具有给定增量的数字范围

标签 python file list matlab

我想知道列表中是否有等效语句来执行以下操作。在 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);

简而言之,我有一个初始值、一个最终值和一个增量。我需要创建一个数组(我读到它相当于 python 中的列表)并打印到一个文件。

最佳答案

在 Python 中,range(start, stop + 1, step) 可以像 Matlab 的 start:step:stop 命令一样使用。然而,与 Matlab 的功能不同,range 仅在 startstepstop 均为整数时才有效。如果您想要一个处理浮点值的并行函数,请尝试 numpy 中的 arange 命令:

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 不同,rangenp.arange 都希望它们的参数按顺序 startstop ,然后是步骤。另请记住,与 Matlab 语法不同,rangenp.arange 都会在当前值大于或等于 停止值。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html

关于python - 如何创建具有给定增量的数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18325312/

相关文章:

python - 在Python中将列表动态分解为变量

python - Numpy 中浮点值的组件明智比较返回错误结果

php - 多张照片上传php mysql

c++ - 在 Visual Studio 2010 和 Windows 中使用文件描述符

python - "List object not callable"

android - 如何创建订单?

python - Python UnitTest 中的 assertEqual 应该做什么?

python - 在 Python 的 FoxDot 实时编码环境中使用不同的键

Ruby - 如何将 EOF 标记添加到 PDF 文件中或以其他方式绕过 PDF::Reader::MalformedPDFError: PDF 不包含 EOF 标记

list - 无限列表对任何现实世界的应用程序都有用吗?