def poly (x,a):
j=0
ans=[0]*len(x)
while (j<len(x)):
i=0
while(i<len(a)):
ans[j] = ans[j] + a[i]*((x[j])**i)
i=i+1
else:
j=j+1
else:
print ans
a=[1,1,1]
x=[1,1,1]
print poly(x,a)
现在,我希望此文件中的x
来自另一个包含以下程序的文件:
def mult(x,q):
i=0
while(i<len(x)):
x[i] = x[i]*q
i=i+1
else:
print x
x=[1,1,1]
q=2
print mult(x,q)
答案 0 :(得分:0)
也许这是一个可能的解决方案。
首先:在你的函数定义中你有“print ans”和“print x”,我想你想要return语句。即“return ans”和“return x”。 e.g。
def poly (x,a):
j=0
ans=[0]*len(x)
while (j<len(x)):
i=0
while(i<len(a)):
ans[j] = ans[j] + a[i]*((x[j])**i)
i=i+1
else:
j=j+1
else:
return ans # changed print to return
然后,假设您有两个单独的程序文件(让我们称之为poly.py和mult.py),其中给定的函数是单独定义的,您可以编写一个新程序文件(例如polymult.py),看起来像这样:
#start code
# import programs poly.py and mult.py
# this will execute commands in these files
# but gives access to functions defined within
from poly import *
from mult import *
# Main
# define/reset the variables we need/want to use
a=[1,1,1]
x=[1,1,1]
q=2
# pass mult which returns new x into poly
print poly(mult(x,q),a)
#end code
我对上面编写方式的一个警告是,poly.py和mult.py文件必须与导入它们的程序位于同一目录/文件夹中。 (一个简单的替代方法是简单地定义函数(粘贴它们)代替import语句)
另外,如果您只想将它们用作我的示例中的导入函数,则可以删除除实际函数def之外的所有代码。否则,当您执行polymult.py时,您将看到在导入poly.py和mult.py期间执行的额外屏幕打印