您能用python“导出”输出结果吗?

2024-04-25 23:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我计算五个随机整数列表并将其保存到变量rands,如下所示:

rands=[]
for _ in range(5):
    rands.append([random.randint(0,10) for _ in range(5)])

然后我打印它:

[[9, 1, 1, 6, 10], [4, 7, 8, 7, 6], [10, 2, 3, 4, 5], [1, 2, 2, 6, 7], [9, 1, 3, 6, 3]]

然后我再做一次:

rands2=[]
for _ in range(5):
    rands2.append([random.randint(0,10) for _ in range(5)])

并打印:

[[4, 8, 4, 8, 7], [5, 3, 5, 8, 3], [2, 0, 6, 3, 0], [1, 3, 2, 2, 6], [9, 10, 3, 10, 0]]

我可以将这两个列表“导出”到test.py文件中,以便以后可以导入它们吗?像这样:

rands=[[9, 1, 1, 6, 10], [4, 7, 8, 7, 6], [10, 2, 3, 4, 5], [1, 2, 2, 6, 7], [9, 1, 3, 6, 3]]
rands2=[[4, 8, 4, 8, 7], [5, 3, 5, 8, 3], [2, 0, 6, 3, 0], [1, 3, 2, 2, 6], [9, 10, 3, 10, 0]]

这样我就可以在需要这些变量时执行from test import rands, rands2

提前谢谢


Tags: 文件infrompytestimport列表for
2条回答

为此,可以使用Pickle模块

  1. 在原始python文件中:
import pickle

my_object = [1, 2, 3, 4]

with open('filename', 'wb') as file:
    pickle.dump(my_object, file)
  1. 从新文件(test.py)中读取此二进制文件以获取对象:
import pickle

with open('filename', 'rb') as file:
    my_object = pickle.load(file)

然后您将能够使用以下命令导入此对象:from test import my_object

您可以创建一个test.py,其中包括您编写的randsrands2,然后调用from test import rands, rands2在与test.py相同的目录下的另一个python程序中使用这些变量。如果要从其他地方导入test.py,它必须位于the module search path

进一步阅读: https://docs.python.org/3/tutorial/modules.html

要使用export变量,必须在python脚本中定义它们。使用Python编写更多的Python通常是个坏主意。您可能想做的是将这些变量导出到JSON文件中,然后从该JSON文件中读取它们

进一步阅读JSON导出和导入: https://docs.python.org/3/library/json.html

JSON是一种用于存储数据的特殊格式,可以方便地为计算机加载/卸载数据。您可以将randsrands2存储在Python dict中,然后将该字典导出到JSON文件

例如:

rands=[[9, 1, 1, 6, 10], [4, 7, 8, 7, 6], [10, 2, 3, 4, 5], [1, 2, 2, 6, 7], [9, 1, 3, 6, 3]]
rands2=[[4, 8, 4, 8, 7], [5, 3, 5, 8, 3], [2, 0, 6, 3, 0], [1, 3, 2, 2, 6], [9, 10, 3, 10, 0]]



import json

# Store the data
with open('test.json', 'w+') as fout:
    json.dump({'rands':rands, 'rands2':rands2}, fout)

# Retrieve the data
with open('test.json') as fin:
    test = json.load(fin)
    rands = test['rands']
    rands2 = test['rands2']

相关问题 更多 >