How to write an uninitialized list

Asked 2 years ago, Updated 2 years ago, 211 views

Sorry for the rudimentary question

a=[ ]
a.append(1)

In this case, it is initialized with a=[] every time and [1] is output every time it is executed, but
I would like to know how to write the additional code [1], [1,1], [1,1,1]... every time I run it.

python

2022-09-30 21:59

2 Answers

"Every Run" is different for "Every Run in a Loop" or "Every Run Function" or "Every Run Python."

Add every time you run in a loop

a=[] initializes out of the loop.

a=[ ]
for i in range (3):
    a.append(i)

print(a)#[0,1,2]

Add every time you run a function

Initialize a=[] outside the function as an argument for the function.
(It doesn't have to be an argument, but it can be written in a clearer way.)

a=[ ]
def append_list(a,i):
    a.append(i)

[append_list(a,i)for i in range(3)]
print(a)#[0,1,2]

Add every python run

python test.py always initializes the variable.
Whenever you want to return a variable value for each run, you must save it somewhere (serialization or configuration files, databases, registry etc. etc. below).

Python provides an easy way to save and restore variables as binary object files, often referred to as "serialization" regardless of the programming language.
Use the pickle package for serialization.

You can use this mechanism to serialize a and save it to the test.pickle file at python test.py runtime, and restore objects in the a list from that file each time you run it.

import pickle

try:
    a=pickle.load(open("test.pickle", "rb"))#Restore
except:
    a = [ ] Initialize the variable if the read fails, for example, test.pickle does not exist

value = max(a)+1 iflen(a)>0 else0
a.append(value)
print(a)

pickle.dump(a,open("test.pickle","wb")")#Save

Run Results

>python test.py
[0]
>python test.py
[0, 1]
>python test.py
[0, 1, 2]

References

How to easily invoke the resulting variable
Pickle-Load variable if exists or create and save it


2022-09-30 21:59

It is a common practice to remove the old state at the end of the day, rather than bother to initialize.

Therefore, at the end of the process, you need to save the data in a way that is available for the next boot.At the same time, you must also "open and use the data stored in the previous process" when you try again.

If it's elementary, there's pickle, and if it's a little higher, there's sqlite3.You can build this with __init__, _del__ and create your own list class to achieve your goal.

_init__, _del__ behavior sample

#!/usr/bin/python

class cls1 (object):
    def__init__(self):
        print("__init__")
    def_del__(self):
        print("__del__")

a = cls1()


2022-09-30 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.