简体   繁体   English

如何在 Python 中制作一长串数字

[英]How to make a long list of numbers in Python

My question is about a simple program I wrote it in python.我的问题是关于我用 python 编写的一个简单程序。 I like to create a 'note' file included a list from: "point 100,000" to "point 999999" placed in each lines separately:我喜欢创建一个“note”文件,其中包含一个列表:“point 100,000”到“point 999999”分别放置在每一行中:

point 100,000点 100,000

point 100,001点 100,001

... ...

point 999,999点 999,999

I wrote this code:我写了这段代码:

new = ''
for m in range(100000,999999):
    new = new + 'point ' + str(m) + '\n'
fw = open('list.txt', 'w')
fw.write(new)

It works, but unfortunately it takes about 45 minutes for running.它有效,但不幸的是它需要大约 45 分钟才能运行。 please help me to correct this code.请帮我更正此代码。

Avoid the unnecessary string concatenation, write to the file directly instead:避免不必要的字符串连接,直接写入文件:

with open('list.txt', 'w') as fw:
    for m in range(100000,999999):
        fw.write('point ' + str(m) + '\n')

Use xrange for better performance.使用 xrange 以获得更好的性能。

with open('list.txt', 'w') as fw:
    for m in xrange(100000,999999):
        fw.write('point {}\n'.format(str(m))

Try the following:请尝试以下操作:

with open('lists.txt', 'w') as fw:
    for m in range(100000,999999):
        fw.write('point ' + str(m) + '\n')

Then, you do not need to store all the content in a string before writing it to the file.然后,您无需在将所有内容写入文件之前将其存储在字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM