我在一个函数中创建了一个文本文件。对于学校项目,我必须取得该文本文件,并使用相同的数据放入另一个文本文件“distance”,然后将变量“equation”附加到前一个文本文件中每行的末尾。然而,我坚持如何在第一个函数中使用x,y,z变量,并在不使用全局变量的情况下在第二个函数中使用它们?帮帮我!在Python中使用另一个函数的局部变量?
def readast():
astlist=[]
outFileA=open('asteroids.txt','w')
letter=65
size_of_array=15
astlist=[]*size_of_array
for i in range(0,size_of_array):
x=random.randint(1,1000)
y=random.randint(1,1000)
z=random.randint(1,1000)
outFileA.write ('\n'+chr(letter) + '\t' +(str(x)) + '\t' + (str(y)) +'\t' +(str(z)))
letter= letter+ 1
return x,y,z
outFileA.close()
def distance():
outFileA=open('asteroids.txt','r')
outFileD=open('distance.txt','w')
x= (x**2)
y= (y**2) #these three variables I need to pull from readast
z= (z**2)
equation=math.sqrt(x+y+z)
for row in range(len(outfileA)):
x,y,z=outFileA[row]
outFileD.append(equation)
outFileD.close()
你不必做你自己'的距离()'计算,只需使用['math.hypot()'](https://docs.python.org/2/library/math.html?highlight=hypot#math.hypot)函数即可。 – martineau 2014-11-22 21:35:44
何时使用“距离”功能?它是从'readast'调用的吗? – sleeparrow 2014-11-22 21:37:46
@Adamantite,主函数中调用'distance'函数,这里没有显示。我的教授说每个函数都应该只做一件事,否则我会把追加函数和'readast'放在同一个函数中。距离函数用于创建一个新的文本文件distance.txt,其值与asteroids.txt相同,然后将更多值附加到distance.txt中(如果有意义的话) – Jackie 2014-11-22 21:40:52