Python-不使用if语句重复代码,还有另一种方法吗?

时间:2019-07-04 05:08:59

标签: python refactoring

希望提高我的python和编码技能。我有一个功能,可以向时间添加特定的时间范围。 我通过:

1M, 7D, 6M, 2H, M等。并返回值。我觉得我在重复自己。有没有更Python化的方法呢?


def add_timeframe(time, timeframe):                                                                                                                                     

    if 'H' in timeframe:                                                                                                                                                
    ┆   try:                                                                                                                                                            
    ┆   ┆   period = int(re.sub('\D', '', timeframe))                                                                                                                   
    ┆   ┆   return convert_datetime(time + datetime.timedelta(hours=period))                                                                                            

    ┆   except ValueError:                                                                                                                                              
    ┆   ┆   return convert_datetime(time + datetime.timedelta(hours=1))                                                                                                 


    if 'D' in timeframe:                                                                                                                                                
    ┆   try:                                                                                                                                                            
    ┆   ┆   period = int(re.sub('\D', '', timeframe))                                                                                                                   
    ┆   ┆   return convert_datetime(time + datetime.timedelta(days=period))                                                                                             

    ┆   except ValueError:                                                                                                                                              
    ┆   ┆   return convert_datetime(time + datetime.timedelta(days=1))                                                                                                  


    if 'W' in timeframe:                                                                                                                                                
    ┆   try:                                                                                                                                                            
    ┆   ┆   period = int(re.sub('\D', '', timeframe))                                                                                                                   
    ┆   ┆   return convert_datetime(time + datetime.timedelta(weeks=period))                                                                                            

    ┆   except ValueError:                                                                                                                                              
    ┆   ┆   return convert_datetime(time + datetime.timedelta(weeks=period))                                                                                            


    if 'M' in timeframe:                                                                                                                                                
    ┆   try:                                                                                                                                                            
    ┆   ┆   period = int(re.sub('\D', '', timeframe))                                                                                                                   
    ┆   ┆   return convert_datetime(time + datetime.timedelta(days=365/12*period))                                                                                      

    ┆   except ValueError:                                                                                                                                              
    ┆   ┆   return convert_datetime(time + datetime.timedelta(days=365/12))

2 个答案:

答案 0 :(得分:1)

我通常通过使用字典来避免很多ifs。我将每个条件映射到字典并执行。这是我的第一个建议:

我创建了一个添加几个月的函数,因为timedelta没有它。然后,我使用re获取数字和字母作为元组。因此,“ 4M”将是(“ 4”,“ M”)。然后我将M映射到月份加法,所以4 *(添加月份功能),W映射加周,等等

import calendar
import datetime
import re


# add month hack
def add_month(num_months, date=None):
    '''Add N months'''

    assert num_months > 0, 'Positive N only'

    if date is None:
        date = datetime.datetime.now()

    for num in range(num_months):
        month_days = calendar.monthrange(date.year, date.month)[1]
        dt = date + datetime.timedelta(days=month_days)

        if dt.day != date.day:
             dt.replace(day=1) - datetime.timedelta(days=1)
        else:
            dt

        date = dt
    return dt



def delta(data, pattern):
    # dict instead of lots of ifs

    time_convert = {'M': lambda x : add_month(x),
                   'W': lambda x :datetime.timedelta(weeks=x),
                   'D': lambda x: datetime.timedelta(days=x),
                   'H': lambda x: datetime.timedelta(hours=x),
                          }


    _ = [re.match(pattern, item).groups() for item in data]

    return [time_convert.get(letter)(int(number))for number, letter in _] 

# test 1
data = ['1M', '7D', '4M', '2H']
pattern = '(\d+)(\w+)'

s = delta(data, pattern)
print(s)

如果我们期望得到不干净的数据,则需要创建一个数据准备功能,以确保我们的数据采用我们希望数字写字母的格式。因为如果我们仅接收字母数据,我们的代码将失败。代替try-catch,如果我们只有一个字母,我们可以添加1。这就是我的经历2:

import calendar
import datetime
import re


# add month hack
def add_month(num_months, date=None):
    '''Add N months'''

    assert num_months > 0, 'Positive N only'

    if date is None:
        date = datetime.datetime.now()

    for num in range(num_months):
        month_days = calendar.monthrange(date.year, date.month)[1]
        dt = date + datetime.timedelta(days=month_days)

        if dt.day != date.day:
             dt.replace(day=1) - datetime.timedelta(days=1)
        else:
            dt

        date = dt
    return dt


def data_prep(data, check_patter='\d+'):
    '''Our data preparation happens here'''

    _ = [bool(re.search(check_patter,item)) for item in data]

    for index, truth in enumerate(_):
        if not truth:
            data[index] = '1'+data[index]

    return data




def delta(data, pattern):

    time_convert = {'M': lambda x : add_month(x),
                'W': lambda x :datetime.timedelta(weeks=x),
                'D': lambda x: datetime.timedelta(days=x),
                'H': lambda x: datetime.timedelta(hours=x),
                       }


    # clean data. if M --> 1M
    data = data_prep(data)
    _ = [re.match(pattern, item).groups() for item in data]

    return [time_convert.get(letter)(int(number))for number, letter in _] 


data = ['1M', '7D', '4M', '2H','H']

pattern = '(\d+)(\w+)'


s = delta(data, pattern)

print(s)

这是在data_prep函数中,您将在其中处理所有可能的不洁性:)

答案 1 :(得分:0)

您可以使用re一次提取数字部分和所有句点。.

>>> import re
>>> inp = ["1M", "7D", "6M", "2H", "M"]
>>> [re.findall('(\d)?(M|D|H)', x) for x in inp]
[[('1', 'M')], [('7', 'D')], [('6', 'M')], [('2', 'H')], [('', 'M')]]

>>> extracted = [re.findall('(\d)?(M|D|H)', x) for x in inp]
>>> [(int(x[0][0] or '1'), x[0][1]) for x in extracted if x] # Filter out invalids.
[(1, 'M'), (7, 'D'), (6, 'M'), (2, 'H'), (1, 'M')]

然后您可以在原始代码中使用convert_datetime(..)和其他操作。

PS:我将执行更多的错误检查-上面的代码只是建议使用稍多一些pythonic的方式来做相同的事情。