【问题标题】:Python importing an array from a different filePython从不同的文件导入数组
【发布时间】:2023-03-03 04:30:01
【问题描述】:

所以,我有一个main.py 和一个file.pyfile.py 我有一个函数(例如:

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

和一个数组 words。 )

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

谢谢!

【问题讨论】:

  • 你需要显示更多代码我不知道你在做什么,可能是什么错误
  • 所以,我在 file.py 中有一个函数,它用单词分割字符串,插入数组中。现在,当我想在不同的文件中使用该数组时,它是空的。

标签: arrays python-2.7 function import


【解决方案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']

【讨论】:

  • 谢谢!原来我必须在 s_break() 的参数处添加 list_of_words 数组。
猜你喜欢
  • 1970-01-01
  • 2019-12-30
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
相关资源
最近更新 更多