我試圖使用多個if
語句來檢查某個條件,然後在Python
中使用matplotlib
來繪製一些數據。首先,我在目錄上執行os.walk
以獲取文件列表,然後加載它們以最終繪製並保存圖形。這裏是我的代碼:如果Python中的語句問題
def velocity():
plt.xlabel('$\mathrm{Iterations\/or\/Time}$')
plt.title(r'$\mathrm{Residual\/history}$')
plt.grid(True)
plt.yscale('log')
if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'b', label = 'y-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'g', label = 'z-vel')
plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()
return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)
for path, dirs, files in os.walk(logsDir, topdown=False):
for lf in files:
if 'Ux_0' in lf:
logFile = os.path.join(path, lf)
data_x = np.loadtxt(logFile)
time_x, value_x = data_x[:,0], data_x[:,1]
(time_x, value_x, lf) = velocity()
if 'Uy_0' in lf:
logFile = os.path.join(path, lf)
data_y = np.loadtxt(logFile)
time_y, value_y = data_y[:,0], data_y[:,1]
(time_y, value_y, lf) = velocity()
if 'Uz_0' in lf:
logFile = os.path.join(path, lf)
data_z = np.loadtxt(logFile)
time_z, value_z = data_z[:,0], data_z[:,1]
(time_z, value_z, lf) = velocity()
的logDir
只有三個文件,開始和他們Ux_0
,Uy_0
和Uz_0
。有趣的是,在os.walk
當我print
lf
,我得到文件的訂單Ux_0
,Uz_0
和Uy_0
。現在,函數velocity()
生成的數字僅具有來自Ux_0
和Uz_0
的數據,而不具有來自Uy_0
的數據。然而,在我的函數中,如果Uy_0
和Uz_0
的順序被顛倒,使得我有Uz_0
,緊接在Ux_0
後面,如下所示,我得到所有三個圖。
if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'b', label = 'z-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'g', label = 'y-vel')
plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()
return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)
我不確定是什麼原因造成的。
爲什麼'velocity'返回變量,它從全球範圍發生,並以任何方式不會改變? – zehnpaard 2015-02-05 23:23:57