繁体   English   中英

我可以将值从一个Python文件传递到另一个文件吗?

[英]Can I pass values from one Python file to another?

我试图循环运行另一个文件中的一个文件。 FILEA:

cov_matrix是我从彭博社导入的协方差矩阵,而rets是也从彭博社导入的数据框。

max_vol = [8,9,10]

def func1(weights):
    return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights))

def obj(weights):
    return np.sum(rets.T*weights)

cons = {'type':'ineq', 'fun': func1}
bnds = (0,6) in range 30

def minimixe()
    scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons}

我想对max_vol的多个值运行最小化函数。

我尝试在for循环中运行整个程序,但是即使对于max_vol的值不同,我也会得到相同的结果。 所以我尝试从另一个文件B调用整个文件A。

import fileA
    for i in range(8,10):
    fileA.minimize()

但我得到我未定义的错误。

我尝试直接传递我以最小化,但func1的列表索引超出范围错误

def func1(weights):
    return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights))

cons = {'type':'ineq', 'fun': func1}
bnds = (0,6) in range 30

def minimixe()
    scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons}

for i in range(8,10)
    minimize(i)    

我该如何处理?

原因是scipy.minimize使用默认的args调用func1 ,您可以使用functools.partiali添加为位置arg,但仍将其传递给scipy.minimize

from functools import partial

# add that argument here so you don't get a nameError
def func1(i, weights):
    return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights))

# add the argument here so that you can call it in fileB
def minimize(i):
    # partial will return a new function with the first positional argument
    # specified already
    cons = {'type':'ineq', 'fun': partial(func1, i)}
    # now this can work as expected
    scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons}

这样就可以将i作为第一个位置arg传递给func1 ,而scipy无需明确地这样做。 您现在可以这样称呼它:

import fileA

for i in range(8, 10):
    fileA.minimize(i)

暂无
暂无

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

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