Python从不同的文件导入数组

时间:2017-02-18 12:09:37

标签: arrays python-2.7 function import

所以,我有main.pyfile.pyfile.py我有一个功能(例如:

def s_break(message):
     words = message.split(" ")

和数组words。 )

当我使用:main.py将单词数组导入from "filename" import words时,我收到数组为空。为什么呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要实际调用s_break函数,否则您只需获取空列表/数组。

test_file.py:

message = 'a sample string this represents'
list_of_words = []

def s_break(message):
    words = message.split(" ")
    for w in words:
        list_of_words.append(w)

s_break(message)    # call the function to populate the list

然后在 main.py

from test_file import list_of_words

print list_of_words

输出:

>>> ['a', 'sample', 'string', 'this', 'represents']