我尝试创建一个带有内部循环的函数。该脚本在没有函数的情况下起作用,但是声明python函数不起作用。(原始脚本更长,但是我认为这部分就足够了)
import numpy as np
import math as mt
from sympy import*
import fractions
init_printing(use_latex='mathjax')
PHnumbers=4
PHnumbers2=2
statetype= 1
for d in range(1,9):
modes=d+1
if statetype==1:
comb=modes
elif statetype==2:
comb=int((modes*(modes+1))/2)
exec(f'Phases{d}=[]'), exec(f'Phasesv{d}=[]')
for i in range(modes):
exec(f'theta_{i+1}= symbols(\'theta_{i+1}\', real=True)')
exec(f'Phases{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'Phasesv{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'v{i+1}=[[0]]*modes')
exec(f'Phasesv{d}[0]*=0')
for i in range(modes):
exec(f'globals()[\'\'.join([\'v\',str(i+1)])][i]=[PHnumbers*diff(Phasesv{d}[i],Phases{d}[i])]')
conteo = d
for j in range(modes):
for i in range(modes):
if j<i:
conteo = conteo + 1
exec(f'v{conteo+1}=[[0]]*modes')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][i]=[PHnumbers2*diff(Phasesv{d}[i],Phases{d}[i])]')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][j]=[PHnumbers2*diff(Phasesv{d}[j],Phases{d}[j])]')
exec(f'Vec{d}=[]'),exec(f'Coeff{d}=[]'), exec(f'Nii{d}=[]'), exec(f'Nij{d}=[]')
for i in range(comb):
exec(f'Vec{d}.append(globals()[\'\'.join([\'v\',str(i+1)])])')
对于范围(len(Vec4))中的i:print(Vec4 [i])先前的脚本有效,到目前为止没有问题。现在,我声明python函数:
def metro(PHnumbers):
statetype=1
PHnumbers2=2
for d in range(1,9):
modes=d+1
if statetype==1:
comb=modes
elif statetype==2:
comb=int((modes*(modes+1))/2)
exec(f'Phases{d}=[]'), exec(f'Phasesv{d}=[]')
for i in range(modes):
exec(f'theta_{i+1}= symbols(\'theta_{i+1}\', real=True)')
exec(f'Phases{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'Phasesv{d}.append(globals()[\'\'.join([\'theta_\',str(i+1)])])')
exec(f'v{i+1}=[[0]]*modes')
exec(f'Phasesv{d}[0]*=0')
for i in range(modes):
exec(f'globals()[\'\'.join([\'v\',str(i+1)])][i]=[PHnumbers*diff(Phasesv{d}[i],Phases{d}[i])]')
conteo = d
for j in range(modes):
for i in range(modes):
if j<i:
conteo = conteo + 1
exec(f'v{conteo+1}=[[0]]*modes')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][i]=[PHnumbers2*diff(Phasesv{d}[i],Phases{d}[i])]')
exec(f'globals()[\'\'.join([\'v\',str(conteo+1)])][j]=[PHnumbers2*diff(Phasesv{d}[j],Phases{d}[j])]')
exec(f'Vec{d}=[]'),exec(f'Coeff{d}=[]'), exec(f'Nii{d}=[]'), exec(f'Nij{d}=[]')
for i in range(comb):
exec(f'Vec{d}.append(globals()[\'\'.join([\'v\',str(i+1)])])')
for i in range(len(Vec4)):
print(Vec4[i])
第二个代码显示问题:“ theta_1未定义”
从文档中exec
:
注意:默认本地语言的行为与下面对函数locals()的描述相同:不应尝试对默认本地语言字典进行修改。如果需要在函数exec()返回后查看代码对本地语言的影响,请传递一个明确的本地语言字典。
因此,从本质上讲exec
,出于解释器效率的原因,您不能使用本地变量。相同的限制不适用于全局变量,这就是您的第一个版本起作用的原因。
至于该怎么做:很好,这些exec
电话是非常不必要的。只需正常执行Python代码,而无需进行混乱的exec
调用。老实说,它可能也会运行得更快。在所有将相似名称的变量分类在一起的地方,只需根据用例将它们替换为单个数组或字典即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句