我是python的新手,请帮助我将数组输出到.txt文件。 我的二维数组输出很大。
这是我的代码:
num_of_mangoes[]
for i in range(shops):
num_of_mangoes.append([])
for j in range(fruits):
num_of_mangoes[i].append(j)
return num_of_mangoes
其他信息:
200000
500
答案 0 :(得分:0)
假设实际代码为:
num_of_mangoes = []
for i in range(shops):
num_of_mangoes.append([])
for j in range(fruits):
num_of_mangoes[i].append(j)
我建议使用json module将其导出到文件中
import json
with open("num_of_mangoes.txt", "w") as file:
json.dump(file, num_of_mangoes)
如果您想从文件中读取列表,可以执行以下操作:
with open("num_of_mangoes.txt", "r") as file:
num_of_mangoes = json.load(file)
答案 1 :(得分:0)
尝试使用此代替:
# we'll use this module later on
import json
# define the number of shops and fruits
shops, fruits = 200000, 500
# create the "num_of_mangoes" list using a list comprehension
num_of_mangoes = [[j for j in range(fruits)] for i in range(shops)]
# open the file (create if not exists), write to it, then close it
f = open("num_of_mangoes.txt", "w")
# NOTE: the "separators" and "indent" arguments are used to minify the json
f.write(json.dumps(num_of_mangoes, separators = (',', ':'), indent = 0))
f.close()
这是同一代码的单线版本:
import json; with open("num_of_mangoes.txt", "w") as f: f.write(json.dumps([[j for j in range(500)] for i in range(200000)], separators = (',', ':'), indent = 0))
缩小:
import json;with open("num_of_mangoes.txt","w") as f:f.write(json.dumps([[j for j in range(500)] for i in range(200000)],separators=(',',':'),indent=0))
警告:您的JSON文件将变得(非常可笑)大,请不要使用像Atom这样的文本编辑器打开它,它可能会冻结您的计算机,请使用{{1} },cat
或head
命令。
警告::鉴于您拥有tail
(二十万家)商店,此列表将需要一段时间才能创建,因此建议您降低该数字以进行测试。
祝你好运。