简体   繁体   English

在Python模块中初始化静态列表的最佳方法

[英]Best way to initialize a static list in a Python module

I have two Python modules: user.py and lib.py. 我有两个Python模块:user.py和lib.py. lib.py contains certain functions that are written in the following way and are called from the user.py module: lib.py包含以下列方式编写并从user.py模块调用的某些函数:

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. 现在我想在lib.py模块中添加一个静态字符串列表,以便lib.py模块中的所有函数都可以使用它们。 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: 只需使用Python列表文字:

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. 如果您所做的只是创建预定大小和内容的列表,则无需调用list.append() 4次。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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