简体   繁体   English

如何让我的 python function 从 another.py 文件中读取数据

[英]How do I get my python function to read data from another .py file

Note: I have simplified my problem below.注意:我在下面简化了我的问题。 Also, I am using Spyder.另外,我正在使用 Spyder。

I have saved a function called testFunc in a.py file.我在 .py 文件中保存了一个名为 testFunc 的 function。 This function gives you the mean value of a subset of a list of numbers.这个 function 为您提供了数字列表子集的平均值。

This is the function, FYI:这是 function,仅供参考:

def testFunc(X):
    subSet = List[0:X]
    Output = sum(subSet)/len(subSet)
    return Output

In my master.py file, I load the data:在我的 master.py 文件中,我加载了数据:

List = [1, 2, 3, 4]

I then pull the testFunc function from a separate folder:然后我从一个单独的文件夹中提取 testFunc function:

%run '/Users/mak/Dropbox/Python/My functions/getScore.py'

Then I try to run my data through my function:然后我尝试通过我的 function 运行我的数据:

testFunc(2)

However I get a message但是我收到一条消息

NameError: name 'List' is not defined

When I run the function and define the List in the same.py file, I do not have this problem.当我运行 function 并在 same.py 文件中定义列表时,我没有这个问题。 But I do not want to do this as my code is very long.但我不想这样做,因为我的代码很长。

The other thing I can do is define the List as part of the function.我可以做的另一件事是将列表定义为 function 的一部分。 But I am wary of doing this as my actual dataset (List) is massive and pulling it everytime I want to run this function seems less than elegant.但我对这样做持谨慎态度,因为我的实际数据集(列表)很大,每次我想运行这个 function 时都会拉它看起来不够优雅。

Is there a third way?有第三种方法吗?

You need to import the list before you can use it:您需要先import列表,然后才能使用它:

master.py:大师.py:

x_lst = [1, 2, 3, 4]

test.py:测试.py:

from master import x_lst

def testFunc(X):
    subSet = x_lst[0:X]
    Output = sum(subSet)/len(subSet)
    return Output

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

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