简体   繁体   中英

Best way to initialize a static list in a Python module

I have two Python modules: user.py and lib.py. lib.py contains certain functions that are written in the following way and are called from the user.py module:

def foo1():
    pass

def foo2():
    pass

def foo3():
    pass

Now I want to add a static list of strings in the lib.py module such that all the functions in lib.py module can use them. I want to strictly initialize the string list in the following way:

string_list = []
string_list.append('string1')
string_list.append('string2')
string_list.append('string3')
string_list.append('string4')

What is the most Pythonic way to achieve this? Would it be possible to do something like this that would work just fine?

string_list = []
string_list.append('string1')
string_list.append('string2')
string_list.append('string3')
string_list.append('string4')

def foo1():
        print string_list[0]

    def foo2():
        print string_list[1]

    def foo3():
        print string_list[2]

Just use a Python list literal:

string_list = ['string1', 'string2', 'string3', 'string4']

No need to call list.append() 4 times if all you are doing is create list of predetermined size and contents.

在这种情况下,您还可以使用合成...

stringList = ['string'+str(i+1) for i in range(4)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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