How to create a range of numbers with a given increment

后端 未结 6 944
故里飘歌
故里飘歌 2021-01-15 15:26

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          


        
6条回答
  •  半阙折子戏
    2021-01-15 15:50

    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):

    1
    6
    11
    16
    21
    26
    31
    36
    41
    46
    

    NOTE: in Python 2.x a range() returns a list, in Python 3.x a range() returns an immutable sequence iterator, and if you want to get a list you have to write list(range())

提交回复
热议问题