首页 > 解决方案 > For循环迭代器作为Python中的变量

问题描述

我有以下代码:

import control
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

s=control.tf([1,0],1)

freqs=np.logspace(-1,2,5)

plant=1/(s*s)
plant_PI=1/(s*s)*(1+1/10/s)
plant_D=1/(s*s)*(1+s/(1/3))/(1+s/(1*3))/3

compare_responses_gain=["mag_plant","mag_plant_PI","mag_plant_D"]
compare_responses_phase=["phase_plant","phase_plant_PI","phase_plant_D"]

mag_plant,phase_plant,omega_plant=plant.freqresp(freqs)
mag_plant_PI,phase_plant_PI,omega_plant_PI=plant_PI.freqresp(freqs)
mag_plant_D,phase_plant_D,omega_plant_D=plant_D.freqresp(freqs)
fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)

for i in compare_responses_gain:
    ax1.plot(freqs,np.squeeze((i),axis=(3,)))

for i in compare_responses_phase:
    ax2.plot(freqs,np.squeeze((i),axis=(3,)))

plt.show()

我想要的是在 for 循环中,“i”作为对 mag_plant 等变量的引用,它是 freqresp 方法的输出。但是,这不起作用,因为“i”被视为字符串。有谁知道如何解决这个问题?我知道我可以在没有 for 循环的情况下完成作业,但我想学习一个更优雅的解决方案。

标签: pythonloops

解决方案


You could just make a list of the return values instead of strings:

compare_responses_gain=[mag_plant,mag_plant_PI,mag_plant_D]

In fact, I'd take this a step further and put your original plant_* varialbes in a list:

plants = [plant, plant_PI, plant_D]

Now you can plot all the data in a single loop:

fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)

for plant in plants:
    mag, phase = plant.freqresp(freqs)
    ax1.plot(freqs,np.squeeze((mag),axis=(3,)))
    ax2.plot(freqs,np.squeeze((phase),axis=(3,)))

plt.show()

推荐阅读