Python中的If语句问题

2024-04-19 09:26:30 发布

您现在位置: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之后,当我printlf时,我得到的文件顺序是Ux_0Uz_0Uy_0。现在,由函数velocity()生成的图形只有来自Ux_0Uz_0的数据,而不是Uy_0。但是,在我的函数中,如果Uy_0Uz_0的顺序颠倒,使得我在Ux_0之后有Uz_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)

我不知道是什么原因造成的。你知道吗


Tags: pathindataiftimevalueosplt
2条回答

虽然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()

你只会返回相同的值,其余的值是不可到达的,因此如果你在你的if中设置值,基于你认为你从你的速度函数得到不同的值,你不会:

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

函数在碰到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]等。。提取和分组任何你想要的。你知道吗

相关问题 更多 >