Python将字符串转换为变量然后在函数中使用

时间:2018-03-21 19:54:27

标签: python arrays function type-conversion generator

我已经为NN 0到n生成了pN的变量名:

p0, p1, p2, p3, p4,....,pn

到目前为止,我得到了:

P = ['p0', 'p1', 'p2',..., 'pn']

我现在要做的是将它们转换为变量名称,以便在函数中调用和使用。 转换' p0'对于p0,依此类推

中的所有值
P = ['p0', 'p1', 'p2',..., 'pn'] 

所以它变成

P = [p0, p1, p2,..., pn]

然后使用变量生成函数:

Fi = P[i]/2

即:

F0 = p0/2
F1 = p1/2
F2 = p2/2

问题是我不知道如何转换' pn' pn正确,然后生成基于pn的函数。我怎么做?或者说,我做错了什么?

这是我得到的:

# Define the constants
# ====================
k = 1
m = 1

# Generate the names
# ==================
n = 10 # Number of terms
P = [] # Array for momenta names
Q = [] # Array for positon names
for i in range (n): # Generate the names for
    p = "p"+str(i)  # momentum
    q = "q"+str(i)  # positon
    # Convert the names into variales
    exec("%s = %d" % p)
    exec("%s = %d" % q)
    # Put the names into the arrays
    P.append(p)
    Q.append(q)
# Print the names out for error checking
print(P)
print(Q)

# Generate the functions
# ======================
Q_dot = []

for i in range(n):
    def Q_dot(P[i]):
        q_dot = P[i] / m
        Q_dot.append(q_dot)
    i += 1

注意:我想将变量保留为变量,因为我使用这些函数来求解微分方程组。我的目标是创建一个具有相同格式的微分方程列表。

0 个答案:

没有答案