If 语句在 Python 中发出

If statement issues in Python

我正在尝试使用多个 if 语句来检查特定条件,然后使用 Python 中的 matplotlib 绘制一些数据。首先,我在目录上执行 os.walk 以获取文件列表,然后加载它们以最终绘制并保存图形。这是我的代码:

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_0Uy_0Uz_0。有趣的是,在 os.walk 之后,当我 print lf 时,我得到的文件顺序为 Ux_0Uz_0Uy_0。现在,函数 velocity() 生成的图形只有来自 Ux_0Uz_0 的数据,而不是 Uy_0。但是,在我的函数中,如果 Uy_0Uz_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)

我不确定是什么原因造成的。

你只能 return 相同的值,其余的值是无法达到的,所以如果你在你的 if 中设置值是基于认为你从你的速度函数中得到不同的值,你不会:

    return (time_x, value_x, lf)
    return (time_y, value_y, lf) # < unreachable
    return (time_z, value_z, lf) #  < unreachable

函数在遇到 return 语句时结束,因此只要您到达第一个语句,它就会结束。

您可以 return 多个元素:

return (time_x,time_y, time_z value_x, value_y, value_z, lf) 

然后使用切片分配 res = velocity(); a,b,c = res[2],res[3] ,res[4] 等。提取和分组任何你想要的。

虽然 Padraic 关于您的 return 语句没有意义的说法是绝对正确的,但问题的实际原因是您缩进和放置 plt.savefig 命令。

如果您查看 plt.savefig 语句的位置,它只会在您到达最后一个 elif 时执行,即当它在 lf 中找到 Uz_0 时。当 Uz_0 是列表中的第二项时,绘图仅在该点保存,因此最后一个数据集被绘制但未保存。

你可能应该有一个 save_velocity() 函数,你 运行 在最后。

def velocity():
    #Rows omitted for succinctness' sake

    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')

    return (time_x, value_x, lf)  # Do Padraic's fixes here!
    return (time_y, value_y, lf)
    return (time_z, value_z, lf)

def save_velocity():
    plt.legend()
    plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
    plt.close() 

for path, dirs, files in os.walk(logsDir, topdown=False):
    for lf in files:
        #Rows omitted for succinctness' sake
        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()

save_velocity()

一些代码清理:

def velocity(time, value, lf):
    plt.xlabel('$\mathrm{Iterations\/or\/Time}$')
    plt.title(r'$\mathrm{Residual\/history}$')
    plt.grid(True)
    plt.yscale('log')

    if 'Ux_0' in lf:
        velocity_color = 'r'
        velocity_label = 'x-vel'
    elif 'Uy_0' in lf:
        velocity_color = 'b'
        velocity_label = 'y-vel'
    elif 'Uz_0' in lf:
        velocity_color = 'g'
        velocity_label = 'z-vel'

    print "Entered"
    plt.plot(time, value, color = velocity_color, label = velocity_label)

    return time, value, lf

def save_velocity():
    plt.legend()
    plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
    plt.close() 

for path, dirs, files in os.walk(logsDir, topdown=False):
    for lf in files:
        if any((filename in lf) for filename in ('Ux_0', 'Uy_0', 'Uz_0')):
            logFile = os.path.join(path, lf)
            data = np.loadtxt(logFile)
            time, value = data[:,0], data[:,1]
            (time, value, lf) = velocity(time, value, lf) # Not sure why you return any value at all here, do you use these values later in some way?

save_velocity()