如何避免在定义中使用很多if语句?

时间:2018-07-15 18:08:59

标签: python if-statement optimization refactoring

我有一个创建网址列表的功能。功能正常。但是我不喜欢这个函数的样子:

def prepareadres(city,y,m,d):
    month = [31,28,31,30,31,30,31,31,30,31,30,31]
    d = d + 1
    d0 = 0
    m0 = 0
    if (d > month[0]):
        d = d - month[0]
        m = m + 1
    if (d > month[1]):
        d = d - month[1]
        m = m + 1
    if (d > month[2]):
        d = d - month[2]
        m = m + 1
    if (d > month[3]):
        d = d - month[3]
        m = m + 1
    if (d > month[4]):
        d = d - month[4]
        m = m + 1
    if (d > month[5]):
        d = d - month[5]
        m = m + 1
    if (d > month[6]):
        d = d - month[6]
        m = m + 1
    if (d > month[7]):
        d = d - month[7]
        m = m + 1
    if (d > month[8]):
        d = d - month[8]
        m = m + 1
    if (d > month[9]):
        d = d - month[9]
        m = m + 1
    if (d > month[10]):
        d = d - month[10]
        m = m + 1
    if (d > month[11]):
        d = d - month[11]
        m = m + 1
    if d == sum(month):    
        print("year complete")
        #print(df.iloc[0, :-2])
    if (m < 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m0) + str(m) + "-" + str(d0) + str(d)
    elif (m < 10) and (d >= 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-"+ str(m0) + str(m) + "-" + str(d)
    elif (m >= 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d0) + str(d)   
    else:
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d)
    #print(adres)
    return adres
正如我提到的,

代码看起来很糟糕,我使用了很多if语句并希望简化这一过程。您能建议更优雅的方式来编写此定义,避免使用if语句吗?

1 个答案:

答案 0 :(得分:1)

使用for循环迭代几个月:

def prepareadres(city,y,m,d):
    months = [31,28,31,30,31,30,31,31,30,31,30,31]
    d = d + 1
    d0 = 0
    m0 = 0
    for month in months:
        if d > month:
             d = d - month
             m += 1
    if d == sum(months):    
        print("year complete")
        #print(df.iloc[0, :-2])
    if (m < 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m0) + str(m) + "-" + str(d0) + str(d)
    elif (m < 10) and (d >= 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-"+ str(m0) + str(m) + "-" + str(d)
    elif (m >= 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d0) + str(d)   
    else:
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d)
    #print(adres)
    return adres