分配

2013-06-02 19 views
1

之前引用的Python局部變量我已經創建了一些代碼:分配

import numpy as np 
Length=(2.7)*10**-3 
Nx=4 
x = np.linspace(0, Length, Nx+1) # mesh points in space 
t1=110 
t2=100 
m=((t2-t1)/Length) 
T=5 
N=5   
t = np.linspace(0, T, N+1) 
Coeff=0.5 
b=0.2 
tamb = 20 
u = np.zeros(Nx+1) 
u_1 = np.zeros(Nx+1) 
for i in range(0, Nx+1): 
    u_1[i] = m*(x[i])+t1 
#print u_1 
r=[] 
for n in range(0, N+1): 
# Compute u at inner mesh points 
for i in range(0,1): 
    u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i] 
for i in range(1,Nx): 
    u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i] 
for i in range(Nx,Nx+1): 
    u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i] 
# Switch variables before next step 
u_1, u = u, u_1 
r.append(u.copy()) 
print r[5] 

輸出代碼:

[ 78.1562 94.1595 96.82 102.6375 102.125 ] 

使用我已創建適用於陣列的功能的代碼:

def function(data,time): 
    import numpy as np 
    Values=data[n] 
    Length=(Values[2])*10**-3 
    Nx=4 
    x = np.linspace(0, Length, Nx+1) # mesh points in space 
    t1=Values[0] 
    t2=Values[1] 
    m=((t2-t1)/Length) 
    T=time[5] 
    N=5   
    t = np.linspace(0, T, N+1) 
    Coeff=0.5 
    b=0.2 
    tamb = 20 
    u = np.zeros(Nx+1) 
    u_1 = np.zeros(Nx+1) 
    for i in range(0, Nx+1): 
     u_1[i] = m*(x[i])+t1 
    #print u_1 
    r=[] 
    for n in range(0, N+1): 
    # Compute u at inner mesh points 
     for i in range(0,1): 
     u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i] 
     for i in range(1,Nx): 
     u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i] 
     for i in range(Nx,Nx+1): 
     u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i] 
    # Switch variables before next step 
     u_1, u = u, u_1 
     r.append(u.copy()) 
    return r 
import numpy as np 

#arrays 
data=np.array(((110,100,2.5),(112,105,2.6),(115,109,2.7))) 
time=np.array((0,1,2,3,4,5)) 
#apply function to array 
for n in range(len(data)): 
    r = function(data,time) 
    print r[5] 

第一代碼工作正常,但是當我使用函數(第二代碼)應用代碼時,如果我告訴我得到以下e rror:

Traceback (most recent call last): 
File "C:/Users/a/Desktop/functiontrial3.py", line 39, in <module> 
r = function(data,time) 
File "C:/Users/a/Desktop/functiontrial3.py", line 3, in function 
Values=data[n] 
UnboundLocalError: local variable 'n' referenced before assignment 

我需要做些什麼才能使下面的代碼工作?

回答

0

改變你的函數簽名:

def function(data,time,n): 

,並調用它像這樣:

for n in xrange(len(data)): 
    r = function(data,time,n) 
+0

您的解決方案有效 – Jay

3

您使用的是全球n這裏

Values=data[n] 

您使用n作爲一個局部變量

for n in range(0, N+1): 

Python不會讓你使用n作爲全局和本地在同一範圍內。

是不是認爲n一樣或者它只是變量名稱的重用?

有幾種方法可以解決這個錯誤,但這取決於你的意圖。

+0

您的解釋非常有幫助 – Jay