gpt4 book ai didi

python - 每次代码执行后 python 列表大小持续增加

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:38 24 4
gpt4 key购买 nike

我的代码以一个空列表开始:

l = []

假设我想在每次运行代码时将 5 个元素附加到我的列表中:

l += [0, 0, 0, 0, 0]  
print(l) . # reuslt is l = [0, 0, 0, 0, 0]

代码执行后,此信息丢失。我想知道每次再次运行我的代码时,我的列表如何保持增长五个零。

first run >>> [0, 0, 0, 0, 0]
second run >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
third run >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.
.
.

最佳答案

您需要在运行之间保留数据。一种方法是使用 pickle 模块,我将在这里演示它,因为它非常简单。另一种方法是使用 JSON。这些方法可以保存(或序列化)Python 数据对象。这不同于仅将文本写入文本文件。

import pickle

my_list = [0, 0, 0, 0, 0]

# Save my_list
file = open("save.txt", "wb") # "wb" means write binary (as opposed to plain text)
pickle.dump(my_list, file)
file.close()

# Close and restart your Python session

file = open("save.txt", "rb") # "rb" means read binary
new_list = pickle.load(file)
file.close()

print(new_list) # -> [0, 0, 0, 0, 0]

编辑:您声明您希望每次运行代码时自动添加到列表中。您可以通过在加载后附加然后再次保存来实现此目的。

import pickle

# Create an empty list
my_list = []

# Try to load the existing list in a try block in case the file does not exist:
try:
file = open("save.txt", "rb") # "rb" means read binary
loaded_list = pickle.load(file)
file.close()
my_list += loaded_list
except (OSError, IOError):
print("File does not exist")

# Append to the list as you want
my_list += [0, 0, 0, 0, 0]

# Save the list again
file = open("save.txt", "wb")
pickle.dump(my_list, file)
file.close()

print(my_list) # This will get bigger every time the script in run

关于python - 每次代码执行后 python 列表大小持续增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com