current_quarter函数的哪个实现会更加pythonic?

时间:2014-10-25 21:30:35

标签: python

current_quarter函数的哪个实现会更加pythonic,为什么?

第一个版本似乎更容易扩展。但是,它是一种你不会延伸的功能,因为四分之一的概念不会改变。

在第二个版本中,更容易掌握机制。

def current_quarter(input_date):
    months_baskets = [(1,2,3), (4,5,6), (7,8,9), (10,11,12)]
    quarters = (1,2,3,4)
    for idx, basket in enumerate(months_baskets):
        if input_date.month in basket:
            return quarters[idx]
            break

def current_quarter(input_date):
    if input_date.month in (1, 2, 3):
        return 1
    elif input_date.month in (4, 5, 6):
        return 2
    elif input_date.month in (7, 8, 9):
        return 3
    elif input_date.month in (10, 11, 12):
        return 4

2 个答案:

答案 0 :(得分:2)

两者都不是;以数学方式计算四分之一要简单得多:

def current_quarter(input_date):
    return (input_date.month - 1) // 3 + 1

快速演示:

>>> for month in range(1, 13):
...     quarter = (month - 1) // 3 + 1
...     print 'Month: {0:02d}, Quarter: {1:d}'.format(month, quarter)
... 
Month: 01, Quarter: 1
Month: 02, Quarter: 1
Month: 03, Quarter: 1
Month: 04, Quarter: 2
Month: 05, Quarter: 2
Month: 06, Quarter: 2
Month: 07, Quarter: 3
Month: 08, Quarter: 3
Month: 09, Quarter: 3
Month: 10, Quarter: 4
Month: 11, Quarter: 4
Month: 12, Quarter: 4

答案 1 :(得分:1)

我不确定我是否得到了Martjin试图提出的建议,所以我会采取这种自由来提出我的解决方案

>>> def current_quarter(input_date):
        return (input_date.month - 1) // 3 + 1
>>>
>>> from datetime import datetime
>>> [(m, current_quarter(datetime(2014, m, 1))) for m in range(1,13)]
[(1, 1), (2, 1), (3, 1), (4, 2), (5, 2), (6, 2), (7, 3), (8, 3), (9, 3), (10, 4), (11, 4), (12, 4)]