Python: get all months in range?

后端 未结 9 1197
天涯浪人
天涯浪人 2020-12-15 18:00

I want to get all months between now and August 2010, as a list formatted like this:

[\'2010-08-01\', \'2010-09-01\', .... , \'2016-02-01\']
<
9条回答
  •  孤城傲影
    2020-12-15 18:40

    I don't know whether it's better, but an approach like the following might be considered more 'pythonic':

    months = [
        '{}-{:0>2}-01'.format(year, month)
            for year in xrange(2010, 2016 + 1)
            for month in xrange(1, 12 + 1)
            if not (year <= 2010 and month < 8 or year >= 2016 and month > 2)
    ]
    

    The main differences here are:

    • As we want the iteration(s) to produce a list, use a list comprehension instead of aggregating list elements in a for loop.
    • Instead of explicitly making a distinction between numbers below 10 and numbers 10 and above, use the capabilities of the format specification mini-language for the .format() method of str to specify
      • a field width (the 2 in the {:0>2} place holder)
      • right-alignment within the field (the > in the {:0>2} place holder)
      • zero-padding (the 0 in the {:0>2} place holder)
    • xrange instead of range returns a generator instead of a list, so that the iteration values can be produced as they're being consumed and don't have to be held in memory. (Doesn't matter for ranges this small, but it's a good idea to get used to this in Python 2.) Note: In Python 3, there is no xrange and the range function already returns a generator instead of a list.
    • Make the + 1 for the upper bounds explicit. This makes it easier for human readers of the code to recognize that we want to specify an inclusive bound to a method (range or xrange) that treats the upper bound as exclusive. Otherwise, they might wonder what's the deal with the number 13.

提交回复
热议问题