python - 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 循环的情况下完成作业,但我想学习一个更优雅的解决方案。
解决方案
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()
推荐阅读
- python - 使用 lineplot 用 seaborn 绘制两条线
- node.js - 我在哪里可以找到这个 mongodb 连接功能是如何实现的?
- wix-react-native-navigation - 问:带有自定义组件而不是“三个点”的溢出菜单
- javascript - 如何添加外部 javascript 文件 postman 环境?
- javascript - 从字符串中删除字符会删除某些字母的倍数,但不会删除其他字母
- ios - iPad 上 NavigationLink 的奇怪行为
- svg - svg 鼠标悬停位置的工具提示
- python - 根据下一行列创建列
- hive - 在 Hive2 中向 ORC 表中插入数据
- javascript - 映射文本和 html。职位搜索