簡體   English   中英

如何循環 function arguments

[英]How to loop over function arguments

我試圖找出一個循環遍歷 function arguments 的好方法。 我有下面的代碼,我只是在“3 點”、“5 點”和“7 點”三種不同的情況下強制使用它。 這些案例中的每一個都有相應的變量,例如“P_list_3point”、“xpoints_3point”等。

我知道簡化以下代碼的一種方法是從每個“代碼塊”中創建一個 function,因為它們重復相同的過程,但是我將如何循環 arguments? 就像每個案例(3 點,5 點,7 點)都有一系列對應的向量,我如何自動將這些向量輸入到實際的 function 中? 我只處理三個案例,但是如果我使用 1000 個案例,那么構建它的好方法是什么? 為任何nooby錯誤道歉,我在編碼方面仍然很糟糕

T1 = 298 #incoming temperature, dummy value in K
P1 = 10 #incoming pressure, dummy value in atmospheres
M1 = 1.4349 #inlet mach number
gamma = 1.4


P_list_3point = np.zeros(len(xpoints_3point)) 
T_list_3point = np.zeros(len(xpoints_3point)) 
M_list_3point = ypoints_3point
for i in range(len(xpoints_3point)):
    P_list_3point[i] = SolveP(P1, M_list_3point[i], gamma)
    T_list_3point[i] = SolveT(T1, M_list_3point[i], gamma)
    
    
    
P_list_5point = np.zeros(len(xpoints_5point)) 
T_list_5point = np.zeros(len(xpoints_5point)) 
M_list_5point = ypoints_5point
for i in range(len(xpoints_5point)):
    P_list_5point[i] = SolveP(P1, M_list_5point[i], gamma)
    T_list_5point[i] = SolveT(T1, M_list_5point[i], gamma)
    
    
    
P_list_7point = np.zeros(len(xpoints_7point)) 
T_list_7point = np.zeros(len(xpoints_7point)) 
M_list_7point = ypoints_7point
for i in range(len(xpoints_7point)):
    P_list_7point[i] = SolveP(P1, M_list_7point[i], gamma)
    T_list_7point[i] = SolveT(T1, M_list_7point[i], gamma)

如果我正確理解您的問題,這是一種簡單的方法。 我假設給出了xpoint_n_points, ypoints_npoint

def xPoints(xpoint_n_points, ypoints_npoint):
    length = len(xpoint_n_points)
    P_list_npoint = np.zeros(length) 
    T_list_npoint = np.zeros(length) 
    M_list_npoint = ypoints_npoint

    for i in range(length):
        P_list_npoint[i] = SolveP(P1, M_list_npoint[i], gamma)
        T_list_npoint[i] = SolveT(T1, M_list_npoint[i], gamma)
    return [P_list_npoint, T_list_npoint]

您可以使用字典來表示每個點變量:

# Create a dictionary to represent the lists
P_list = {}
T_list = {}
M_list = {}

def ProcessPoint(point):
    # Assuming xpoints, ypoints are also dictionary or you can convert it into dictionary
    P_list[point] = np.zeros(len(xpoints[point])) 
    T_list[point] = np.zeros(len(xpoints[point])) 
    M_list[point] = ypoints[point]
    for i in range(len(xpoints[point])):
        P_list[point][i] = SolveP(P1, M_list[point][i], gamma)
        T_list[point][i] = SolveT(T1, M_list[point][i], gamma)

# Then you can call the function for each points
ProcessPoint(3)
ProcessPoint(5)
ProcessPoint(7)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM